Reputation: 329
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!
Upvotes: 1
Views: 4631
Reputation: 684
Is there a reason you are using input redirection? Since you asked if there was a better way, I would suggest simply passing the name of the file that you want to read as an argument. For instance, to read a file foo.txt, you would use
./a.out foo.txt
Here is an example of how this works:
#include <stdio.h>
int main(int argc, char* argv[]) {
if(argc < 2) {
printf("Please pass a filename as an argument\n");
return -1;
}
FILE* fp; // file pointer
char buf[200]; // buffer to hold a line of text
// open file, name stored in argv[1]
if((fp = fopen(argv[1], "r")) == NULL) {
printf("Error opening file %s\n", argv[1]);
return -1;
}
while(fgets(buf, sizeof(buf), fp) != NULL) {
// do stuff with the string, stored in buf
printf("%s", buf);
}
// close the file and exit
fclose(fp);
return 0;
}
Note that argc is an argument counter, and argv[] is an array of arguments. You can pass multiple arguments to your program in this way. Cheers!
Upvotes: 0
Reputation: 14685
You need to scan in the trailing \n on the line with the ints.
momerath:~ mgregory$ cat foo.txt
0 4
IWANTTOREADTHISLINE
IWANTTOREADTHISLINE
IWANTTOREADTHISLINE
IWANTTOREADTHISLINE
momerath:~ mgregory$ cat foo.c
#include <stdlib.h>
#include <stdio.h>
int main(){
int a,b;
char line[100];
scanf("%d %d\n", &a, &b);
while(scanf("%[^\n]%*c", &line) == 1) {
printf("%s\n",line);
}
}
momerath:~ mgregory$ gcc foo.c
foo.c:10:28: warning: format specifies type 'char *' but the argument has type
'char (*)[100]' [-Wformat]
while(scanf("%[^\n]%*c", &line) == 1) {
~~~~ ^~~~~
1 warning generated.
momerath:~ mgregory$ ./a.out < foo.txt
IWANTTOREADTHISLINE
IWANTTOREADTHISLINE
IWANTTOREADTHISLINE
IWANTTOREADTHISLINE
momerath:~ mgregory$
Upvotes: 4