使用 fgets() 从文件中提取行不起作用

using fgets() to extract lines from a file not working

我正在尝试开发一个函数来读取文本文件的每一行并将它们存储在字符串数组 (char**) 中,但是 fgets()似乎不起作用,它总是 return 一个空字符。

这是函数

 char** getLines(FILE* fp){

    char** lines;
    int numberOfLines; //number of lines int the file
    char ch; //aux var
    int i; //counter

    while(!feof(fp)){
        ch = fgetc(fp);
        if( ch == '\n'){
            numberOfLines++;
        }
    }

    lines = malloc(numberOfLines*sizeof(char*));

    if (lines==NULL){
        fprintf(stderr,"Error, malloc failed");
        exit(1);
    }

    for(i = 0; i<numberOfLines; i++){
        lines[i] = malloc(MAX_LENGTH*sizeof(char)); //MAX_LENGTH = 128
    }

    i=0;
    while(fgets(lines[i], MAX_LENGTH,fp)){
        printf("Line %d: %s \n",i,lines[i]);
        i++;
    }

    return lines;

}

该函数永远不会进入 while 循环,因此它不会打印任何内容 我还使用了一个非常简单的输入文件:

test line 1
test line 2
test line 3
test line 4

希望你能帮助我, 提前谢谢你。

在进入 while 循环之前,您已经到了文件的末尾。

看这里http://en.cppreference.com/w/cpp/io/c/rewind

Moves the file position indicator to the beginning of the given file stream. The function is equivalent to std::fseek(stream, 0, SEEK_SET); except that end-of-file and error indicators are cleared. The function drops any effects from previous calls to ungetc.

检查这是否有效:

char** getLines(FILE* fp){
    /* ...... */
    i=0;
    rewind(fp); // Rewind here
    while(fgets(lines[i], MAX_LENGTH,fp)){
        printf("Line %d: %s \n", i, lines[i]); // Also use the index as first parameter
        i++;
    }

    return lines;

}