How to read line by line after i read a text into a buffer?

Fei Xue picture Fei Xue · May 12, 2012 · Viewed 37.9k times · Source

First , I read a text into a buffer by calling fread, and then I want to read it line by line, how to do it? I try to use a sscanf , but it seems not to work.

char textbuf[4096];
char line[256];
FILE *fp;
fp = fopen(argv[1],"r");
memset(textbuf, 0, 4096);
fread(textbuf, 1, 4096, fp);

I know using fgets is a good way. I just want to know weather this method can do the same thing.

Answer

Jack picture Jack · May 12, 2012

Try this:

fgets(textbuf, sizeof(textbuf), fp);

For read line by line you can use: fgets(line, 128, fp) or getline(&line, &size, fp);

EDIT

If you want to read it from a variable, look at strtok() function:

char * line = strtok(strdup(buffer), "\n");
while(line) {
   printf("%s", line);
   line  = strtok(NULL, "\n");
}