How to read line by line after I read the text into the buffer?

Firstly, I read the text into the buffer by calling fread, and then I want to read it in turn, how to do it? I am trying to use sscanf, but it does not seem 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 the weather, this method can do the same.

+5
source share
4 answers

Try the following:

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

To read line by line you can use: fgets(line, 128, fp)orgetline(&line, &size, fp);

EDIT

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

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

You can find the location of the end of line character using strchr () as follows:

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

*eol - . line eol + 1, \r \n , strchr() NULL, , . .

, , 2 , , , , fgets(), .

+5

strtok

char *line;
line = strtok(texbuf, '\n');
+2

: " , fgets - . , ". , , fgets, c. C- , fgets.

, , .

#include <stdio.h>
typedef struct my_state {
 unsigned char * buf;
 int offset;
 int buf_size;
 int left;
 FILE * file;
} my_state_t;
int takeone(my_state_t * state) {
 if ((state->left - state->offset)<=0) {
  if (feof(state->file)) return -1;
  state->left = fread(state->buf,1,state->buf_size,state->file);
  state->offset = 0;
  if (state->left == 0) return -1;
 }
 return state->buf[state->offset++];
}
int getaline(my_state_t * state, char * out, int size) {
 int c;
 c = takeone(state);
 if (c < 0) return 0;
 while (c >=0 && size > 1) {
  *out++ = c;
  --size;
  if (c == '\n') break;
  c = takeone(state);
 }
 *out=0;
 return 1;
}
int main(int argc, char ** argv){
 FILE *fp;
 char textbuf[4096];
 char line[256];
 my_state_t fs;
 fs.buf=textbuf;
 fs.offset=0;
 fs.buf_size=4096;
 fs.left=0;
 fp = (argc>1)? fopen(argv[1],"rb") : stdin;
 fs.file = fp;
 while (getaline(&fs,line,256)) {
  printf("-> %s", line);
 }
 fclose(fp);
}
0

All Articles