Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

fread

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.

like image 601
Fei Xue Avatar asked May 12 '12 02:05

Fei Xue


People also ask

How do I read a file line by line?

Method 1: Read a File Line by Line using readlines() readlines() is used to read all the lines at a single go and then return them as each line a string element in a list. This function can be used for small files, as it reads the whole file content to the memory, then split it into separate lines.

How do you read each line in a file C?

The standard way of reading a line of text in C is to use the fgets function, which is fine if you know in advance how long a line of text could be. You can find all the code examples and the input file at the GitHub repo for this article.


3 Answers

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");
}
like image 76
Jack Avatar answered Oct 06 '22 23:10

Jack


You can find the location of the end-of-line character using strchr() like this:

char *eol = strchr(line, '\n');

Everything before *eol is the first line. Then advance from line to eol + 1, remove any subsequent \r or \n characters, and repeat the process until strchr() returns NULL to indicate there are no more newline characters. At that point, move any remaining data to the beginning of the buffer and read the next chunk from the file.

If you're concerned about efficiency you can avoid moving the data by using 2 buffers and alternating between them, but even the naive method is probably faster than fgets() if the file has many lines.

like image 34
Adam Liss Avatar answered Oct 06 '22 22:10

Adam Liss


how about strtok

char *line;
line = strtok(texbuf, '\n');
like image 23
Musa Avatar answered Oct 06 '22 22:10

Musa