Click here to Skip to main content
Rate this: bad
Please Sign up or sign in to vote.
See more: C
I have coded a function to read in a csv file but half way through the parsing the program crashes giving me errors in strcat.

The errors are at the third field which is phone.I can't spot the error I have made in this read function.Anyone have an idea where I'm going of track here?

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

    //open test.csv to be read
    fptr = fopen("test.csv", "r");
    if( fptr == NULL )
        printf("\nCouldn't open %s...");
    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;
            head->prev = NULL;
            head->next = NULL;
            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))
Posted 26-Apr-13 11:55am
H.Brydon at 26-Apr-13 17:30pm
You should run this with a debug build, and show the error message here, including the stack trace (or failing that, what line of code gives the error?).
Mohibur Rashid at 27-Apr-13 0:25am
Your code is very messy, too many unnecessary action. :)

exactly what line does this fail?
Mohibur Rashid at 27-Apr-13 0:27am
by the way, i have no idea what your!!!! csv file containing, but this is not the right way to parse a csv file
JavamanX at 4-May-13 16:17pm
show the content of your csv file

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
0 Sergey Alexandrovich Kryukov 6,554
1 OriginalGriff 6,258
2 Peter Leow 2,534
3 Maciej Los 2,308
4 Abhinav S 2,274

Advertise | Privacy | Mobile
Web04 | 2.8.150414.1 | Last Updated 26 Apr 2013
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100