You said "I know using fgets is a good way. I just want to know weather this method can do the same thing.", of course you can, you just re-implement fgets as in the c library. The c library doesn't actually read line by line, it reads in a whole chunk and gives you a line when you call fgets.
Not an efficient way, but a sample of the kind of things you have to do.
#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);
}
fgets()
to read the file one line at a time? – Setteragetline()
if you are on system POSIX-compatible.. – Trite