C read file line by line

前端 未结 17 2172
后悔当初
后悔当初 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:03

    Some things wrong with the example:

    • you forgot to add \n to your printfs. Also error messages should go to stderr i.e. fprintf(stderr, ....
    • (not a biggy but) consider using fgetc() rather than getc(). getc() is a macro, fgetc() is a proper function
    • getc() returns an int so ch should be declared as an int. This is important since the comparison with EOF will be handled correctly. Some 8 bit character sets use 0xFF as a valid character (ISO-LATIN-1 would be an example) and EOF which is -1, will be 0xFF if assigned to a char.
    • There is a potential buffer overflow at the line

      lineBuffer[count] = '\0';
      

      If the line is exactly 128 characters long, count is 128 at the point that gets executed.

    • As others have pointed out, line is a locally declared array. You can't return a pointer to it.

    • strncpy(count + 1) will copy at most count + 1 characters but will terminate if it hits '\0' Because you set lineBuffer[count] to '\0' you know it will never get to count + 1. However, if it did, it would not put a terminating '\0' on, so you need to do it. You often see something like the following:

      char buffer [BUFFER_SIZE];
      strncpy(buffer, sourceString, BUFFER_SIZE - 1);
      buffer[BUFFER_SIZE - 1] = '\0';
      
    • if you malloc() a line to return (in place of your local char array), your return type should be char* - drop the const.

提交回复
热议问题