0

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?

1
  • Also. do never us *scanf("%s"), better use fgets() Commented May 16, 2017 at 7:17

2 Answers 2

1

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);
 }
Sign up to request clarification or add additional context in comments.

Comments

0

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.

3 Comments

After removing \n from fscanf(test, "%s\n", custid[i].name);. The result still remain, is there another alternative from fscanf()
Yes. getline() is way better to iterate line by line through a file.
"needs an explicit '\n' to be present in the input to be match, without that, the matching will fail." --> No. The '\n' in the format will not fail fscanf(). It matches 0 or more white-spaces from test. It is not needed here, but it does not cause a failure.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.