1

我编写了一个读取 csv 文件的函数,但在解析过程中途程序崩溃给我 strcat 中的错误。错误出现在第三个字段是 phone。我无法发现我在此读取中犯的错误功能。有人知道我要去哪里吗?

struct contact *readFile( struct contact *ptrList)
{
    struct contact *head, *newContact;
    FILE *fptr;
    char oneLine[CONTACT_MAX];
    char *sn, *fn, *ph, *co;
    head = ptrList;


    //open test.csv to be read
    fptr = fopen("test.csv", "r");

    if( fptr == NULL )
    {
        printf("\nCouldn't open %s...");
        return(ptrList);
    }
    fgets(oneLine, CONTACT_MAX, fptr);

    while( !feof(fptr) )
    {
        fgets(oneLine, CONTACT_MAX, fptr); // process the next line to be tokenized
        if (oneLine[strlen(oneLine) - 1] == '\n')
        {
            oneLine[strlen(oneLine) - 1] = '\0';
        }
        sn = strtok(oneLine, " , ");
        fn = strtok(NULL, " , ");
        ph = strtok(NULL, " , ");
        co = strtok(NULL, " , ");

        if ( head == NULL )
        {
            head = (struct contact *)malloc(sizeof(struct contact));
            ptrList = head;
                strcpy(head->fName,fn);
                strcpy(head->sName,sn);
                strcpy(head->phone,ph);
                strcpy(head->company,co);

            head->prev = NULL;
            head->next = NULL;

        }
        else
        {
            newContact = (struct contact *)malloc(sizeof(struct contact));
            head->next = newContact;
            newContact->prev = head;
            newContact->next = NULL;

            strcpy(newContact->fName, fn);
            strcpy(newContact->sName, sn);
            strcpy(newContact->phone, ph);
            strcpy(newContact->company, co);

            head = newContact;
        } // end of (ptrList == NULL)

    } // end of while( !feof(fptr))
    fclose(fptr);
    return(ptrList);

这就是我定义联系的方式:

struct contact {
                char sName[CONTACT_MAX+1];
                char fName[CONTACT_MAX+1];
                char phone[CONTACT_MAX+1];
                char company[CONTACT_MAX+1];
                struct contact *prev;
                struct contact *next;
                };
4

1 回答 1

1

在这里,我试图总结一下:

sn = strtok(oneLine, " , ");
fn = strtok(NULL, " , ");
ph = strtok(NULL, " , ");
co = strtok(NULL, " , ");

您严重依赖正确的格式,但情况可能并非如此。

sn = strtok(oneLine, " , ");
fn = sn ? strtok(NULL, " , ") : NULL;
ph = fn ? strtok(NULL, " , ") : NULL;
co = ph ? strtok(NULL, " , ") : NULL;

if (!co) continue; // bad string

正如 BLUEPIXY 所说:

printf("\nCouldn't open %s...", "test.csv");

在 C 中,分配看起来更简单:

head = malloc(sizeof(*head));

fgets可能会失败:

if (fgets(oneLine, CONTACT_MAX, fptr) == NULL) break; // error, do something...

和未初始化的head变量(感谢 Kninnug):

struct contact *head = NULL; // otherise it contains garbage
于 2013-04-26T21:07:53.787 回答