Reputation:
I have another Problem, fscanf()
only can read one string even, there is 2 in file, so it just repeat it.
Ex. In file
Name
ID
when I read it.
struct customer {
int id;
char name[100];
};
struct customer custid[100];
int num_cust = 1;
strcpy(custid[num_cust].name, "Name");
num_cust++;
strcpy(custid[num_cust].name, "ID");
When writing:
int i;
for (i = 1; i < 3; i++) {
fprintf(test, "%s\n", custid[i].name);
}
And reading:
for (i = 1; i < 3; i++) {
rewind(test);
fscanf(test, "%s\n", custid[i].name);
printf("%s\n", custid[i].name);
}
The Result:
Name
Name
Process returned 0 (0x0) execution time : 0.007 s
Press any key to continue.
But When I do it with int, you can have 2 different result, which is what I wanted.
is there a fix, or alternative from fscanf()
, since it can't read 2 string?
Upvotes: 0
Views: 62
Reputation: 134336
This is probably, your scanning is failing.
Moral of the story: Always check the return value of scanf()
family for success before trying to use the scanned value.
In your case,
fscanf(test, "%s\n", custid[i].name);
needs an explicit '\n'
to be present in the input to be match, without that, the matching will fail.
Probably you want to remove the '\n'
from the format string in the scanning part.
After that, as mentioned in the other answer by W.Jack, the positioning of rewind()
appears wrong, too. You need to rewind once, before the reading starts. Make the call outside the reading loop.
Upvotes: 0
Reputation: 832
This problem is occurring because you put rewind()
inside the for loop . Place it before the for loop. Then it will work fine.
int i;
for (i = 0; i < 2; i++) {
fprintf(test, "%s\n", custid[i].name);
}
rewind(test);
for (i = 0; i < 2; i++) {
// rewind(test);
fscanf(test, "%s\n", custid[i].name);
printf("%s\n", custid[i].name);
}
Upvotes: 1