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.
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.
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.
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");
}
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.
how about strtok
char *line;
line = strtok(texbuf, '\n');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With