Search code examples
cfgetsstrtok

Reading the file with comma delimiter using fgets() and strtok()


I have a text file with three fields separated by comma. Example of the content of my text file: 12345, true programming newbie, BS ME To load the file into the program, i used the below code.... my problem is that sometimes the code works and sometimes it doesn't (no error message appears the program just closes itself and doesn't continue). i also observed the text file is blank (nothing is written) it automatically closes itself and doesn't continue. Your help would be highly appreciated. Thanks!

int read(){
     FILE *stream = NULL;
     int ctr;
     char linebuffer[45];
     char delims[]=", ";
     char *number[3];
     char *token = NULL;
     stream = fopen("student.txt", "rt");
     if (stream == NULL) stream = fopen("student.txt", "wt");
     else {
          printf("\nReading the student list directory. Wait a moment please...");
          while(!feof(stream)){            
                ctr=0;
                fgets(linebuffer, 46, stream);
                token = strtok(linebuffer, delims);
                while(token != NULL){
                  number[ctr] = linebuffer;
                  token = strtok(NULL, delims); 
                  ctr++;
                }
          recordCtr++;                      
          }                     
     recordCtr--;
     }
     fclose(stream);
}    

Solution

  • You never copy the token once you've found it. You can't copy linebuffer, as the data in there will be overwritten as the next line is loaded.

    This line:

    number[ctr] = linebuffer;
    

    should reference token to save the most recently found token, but it doesn't. It should probably read something like1:

    strcpy(number[ctr], token);
    

    but then you'd have to change the declaration to make sure there's space:

    char number[3][32];
    

    Obviously, this introduces a buffer overrun risk, if there's a very long token it won't fit. How to best handle that is left as an exercise. :)

    1 Why the temporary vector is called "number" when it is used to store two numbers and one string (the name) is beyond me.