Anonymous
Anonymous asked in Computers & InternetProgramming & Design · 2 months ago

c - read words from csv file and represent them as single characters in new file?

So I have a csv file opened in excel and I'm trying to copy everything in that file and write it in a new file with alterations. I have a 4th column filled with a specific food in each row and I want to change it so that it only prints out the first letter of each food in the new file. Like 'Meatballs' should print as 'M'. The problem is I keep getting a segmentation fault and I have no clue what's causing it. I spent hours trying to fix this simple problem with no success. Any help would be appreciated.

    while(fgets(readLine, lineCount, fd)) {

        char* tmp = strdup(readLine);

        if(strcmp(getfield(tmp, 1), "Food") == 0){

            if(strcmp(getfield(tmp, 4), "Meatballs") == 0){

                fprintf(ft, "%c,", 'M');

            }else if(strcmp(getfield(tmp, 4), "Icecream") == 0){

                fprintf(ft, "%c,", 'I');

            }

        }

        fprintf(ft, "\n");

        free(tmp);

    } 

Update:

getfield function:

const char* getfield(char* line, int num){

    const char* tok;

    while(tok = strsep(&line, ","))

    {

        if(!--num) {

            printf("%s\n", tok);

            return tok;

        }

    }

    return NULL;

}

1 Answer

Relevance
  • EddieJ
    Lv 7
    2 months ago
    Favorite Answer

    It's difficult to debug someone else's program when we don't have their input file.

    You also have missing code -- we don't know how the variable used in your fgets () are declared.

    You should try a test program that has the missing code but then just has

    fgets (readLine, lineCount, fd);

    char* tmp = strdup (readLine);

    printf ("%s\n", tmp);

    to verify that you can get the first line correctly.

    In other words, try to step through things.

    Or, do you have a debugger that can help you do that?

Still have questions? Get your answers by asking now.