How to use fgets() and store every line of a file

2019-05-23 14:56发布

I wrote the program below in order to read every line of the file and then store each line in a array of char pointers for later use (like sorting only the pointers not the real strings). But the problem is that it keeps storing the same line.

Lets say that the file is called file.txt and has two(2) lines with text.

  first sentence
  second sentence

The code I wrote is the following:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <unistd.h>

int main(){
    FILE *cf;
    cf = fopen("file.txt", "r");
    char line[101];
    char *lines[2];
    char *eof;

    int i=0;
    while((eof = fgets(line, 101, cf)) != NULL){
        lines[i] = eof;
        i++;
    }

    printf("%s\n", lines[0]);
    printf("%s\n", lines[1]);

    system("pause");
    return 0;
}

The output I get is:

second sentence
second sentence

But I want to get:

first sentence
second sentence

What I am doing wrong here?

-Thanks for your help :-)

3条回答
ら.Afraid
2楼-- · 2019-05-23 15:11

You should use getline(3), e.g.

char* myline = NULL;
size_t mylinesize = 0;
ssize_t mylinelen = 0;
while ((mylinelen = getline(&myline, &mylinesize, cf)) >= 0) {  
    lines[i++] = strdup(myline);
}
free (myline); 
myline = NULL;

and you should consider using readline(3) and the GNU readline library (GPL licensed) for interactive use.

查看更多
倾城 Initia
3楼-- · 2019-05-23 15:25
eof = fgets(line, 101, cf)
while(eof!=NULL)
{
    puts(eof);
    eof=fgets(line,101,cf);
    free(eof);
}
查看更多
Lonely孤独者°
4楼-- · 2019-05-23 15:29

The function fgets doesn't allocate new memory. So in case of success eof == line - that's right, it returns what you passed. You are overwriting it every time.

Try:

while((eof = fgets(line, 101, cf)) != NULL){
    lines[i] = strdup(eof);
    i++;
}

Of course you must remember to free(lines[i]).

查看更多
登录 后发表回答