Click here to Skip to main content
15,891,184 members
Please Sign up or sign in to vote.
2.20/5 (3 votes)
See more:
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?


C#
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...");
        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);
Posted
Comments
H.Brydon 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 27-Apr-13 0:25am    
Your code is very messy, too many unnecessary action. :)

exactly what line does this fail?
Mohibur Rashid 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 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)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900