读取csv文件时函数崩溃

时间:2013-04-26 20:42:06

标签: c text-parsing strtok strcpy

我编写了一个函数来读取一个csv文件,但在解析程序崩溃的一半时给了我strcat中的错误。错误发生在第三个字段是phone.I无法发现错误我已经在这个阅读功能。任何人都知道我在哪里跟踪?

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;
                };

1 个答案:

答案 0 :(得分: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