C read file line by line

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

    In your readLine function, you return a pointer to the line array (Strictly speaking, a pointer to its first character, but the difference is irrelevant here). Since it's an automatic variable (i.e., it's “on the stack”), the memory is reclaimed when the function returns. You see gibberish because printf has put its own stuff on the stack.

    You need to return a dynamically allocated buffer from the function. You already have one, it's lineBuffer; all you have to do is truncate it to the desired length.

        lineBuffer[count] = '\0';
        realloc(lineBuffer, count + 1);
        return lineBuffer;
    }
    

    ADDED (response to follow-up question in comment): readLine returns a pointer to the characters that make up the line. This pointer is what you need to work with the contents of the line. It's also what you must pass to free when you've finished using the memory taken by these characters. Here's how you might use the readLine function:

    char *line = readLine(file);
    printf("LOG: read a line: %s\n", line);
    if (strchr(line, 'a')) { puts("The line contains an a"); }
    /* etc. */
    free(line);
    /* After this point, the memory allocated for the line has been reclaimed.
       You can't use the value of `line` again (though you can assign a new value
       to the `line` variable if you want). */
    

提交回复
热议问题