Search code examples
cfgets

Using fgets to read through file in C


I am trying to read through the file given then tokenize it. The only problem im having is fgets.The file open recieves no errors. I have seen this elsewhere on the site however no matter how i set this up including setting fileLine to a set amount like (char fileline [200]) i get a segmentation fault. Thanks in advance for any help.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>

 int main(int argc, char *argv[]){
    char *fileName = "0";
    char *tokenize, *savePtr;
    struct Record *database= malloc(sizeof(database[0]));
    int recordNum =0;
    char *fileLine = malloc(sizeof(char *));//have replaced with fileline[200] still didnt work
    FILE *fd = open(fileName,O_RDWR);
    if(fd< 0){
        perror("ERROR OPENING FILE");
    }

    while(fgets(fileLine,200,fd) !=NULL){
        printf("%s\n", fileLine);
        tokenize = strtok_r(fileLine,",",&savePtr);
        while(tokenize != NULL){
         //TOKENIZING into a struct
        }
}

Solution

  • Why use open() with FILE? Use fopen() instead.

    #include <stdio.h>
    #include <string.h>
    
    int main(int argc, char *argv[]) {
      char *fileName = "test.txt";
      char *tokenize, *savePtr;
      char fileLine[200] = {0}; // init this to be NULL terminated
      FILE *fd = fopen(fileName, "r");
      if (fd == 0) { // error check, equal to 0 as iharob said, not less than 0
        perror("ERROR OPENING FILE");
        return -1;
      }
    
      while (fgets(fileLine, 200, fd) != NULL) {
        printf("%s\n", fileLine);
        tokenize = strtok_r(fileLine, ",", &savePtr);
        while (tokenize != NULL) {
          tokenize = strtok_r(NULL, ",", &savePtr); // do not forget to pass NULL
          //TOKENIZING into a struct
        }
      }
      fclose(fd);
    
      return 0;
    }
    

    As Weather Vane said, fd < 0 would work if you used open(). However, with fopen(), you should check to see if the pointer is NULL, ecquivalently fd == 0.


    A comparison between this functions that open a file can be found in:

    1. open and fopen function
    2. C fopen vs open

    The way I have it in mind is that fopen() is of higher level.