This is the file contents:
Hello how are you
I have to read until end of line for every line because I have to work on all of these lines individually. I cannot use fread
, fopen
, fscanf
, fgets
.
You could reopen stdin
with freopen
and use getc
to read bytes from the file.
If none of the stream functions from <stdio.h>
are allowed, use the low level POSIX functions open
and read
. The manual pages are available online at man 2 open
and man 2 read
#include <stdio.h>
int main() {
if (freopen("myfile.txt", "r", stdin) != NULL) {
char buf[1000];
int c;
size_t n;
for (n = 0; n < sizeof(buf) - 1; n++) {
c = getc(stdin); // or c = getchar();
if (c == EOF)
break;
buf[n] = c;
}
buf[n] = '\0';
// the file contents are in `buf`, handle these lines as appropriate
}
return 0;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.