What I'm trying to do is to read a file line by line using scanf
. I'm using scanf because the input file needs to be redirected when compiled ex. ./a.out < inputFile
It was successful in the beginning, using:
while(scanf("%[^\n]%*c", &line) == 1) {
printf("%s\n",line);
}
Which printed the file line by line, however when I want to read 2 ints(for example) before reading a bunch of lines ex:
0 4
IWANTTOREADTHISLINE
IWANTTOREADTHISLINE
IWANTTOREADTHISLINE
IWANTTOREADTHISLINE
By using scanf beforehand:
scanf("%d %d", &a, &b);
while(scanf("%[^\n]%*c", &line) == 1) {
printf("%s\n",line);
}
It doesn't work. What's the reason for this? or is there a better way to do it? Thanks!
fgets()
or POSIXgetline()
. Note thatgetline()
deals with most problems of line length as long as the file actually contains lines (you'd still run into problems with a 4 GiB file with no line breaks on a 32-bit machine).