C read file line by line

前端 未结 17 2447
后悔当初
后悔当初 2020-11-22 03:45

I wrote this function to read a line from a file:

const char *readLine(FILE *file) {

    if (file == NULL) {
        printf(\"Error: file pointer is null.\"         


        
17条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-22 04:13

    You should use the ANSI functions for reading a line, eg. fgets. After calling you need free() in calling context, eg:

    ...
    const char *entirecontent=readLine(myFile);
    puts(entirecontent);
    free(entirecontent);
    ...
    
    const char *readLine(FILE *file)
    {
      char *lineBuffer=calloc(1,1), line[128];
    
      if ( !file || !lineBuffer )
      {
        fprintf(stderr,"an ErrorNo 1: ...");
        exit(1);
      }
    
      for(; fgets(line,sizeof line,file) ; strcat(lineBuffer,line) )
      {
        if( strchr(line,'\n') ) *strchr(line,'\n')=0;
        lineBuffer=realloc(lineBuffer,strlen(lineBuffer)+strlen(line)+1);
        if( !lineBuffer )
        {
          fprintf(stderr,"an ErrorNo 2: ...");
          exit(2);
        }
      }
      return lineBuffer;
    }
    

提交回复
热议问题