C read file line by line

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

    readLine() returns pointer to local variable, which causes undefined behaviour.

    To get around you can:

    1. Create variable in caller function and pass its address to readLine()
    2. Allocate memory for line using malloc() - in this case line will be persistent
    3. Use global variable, although it is generally a bad practice

提交回复
热议问题