1

Before anything, english isn't my main language, so, excuse any mistakes.

I started to learn how to use files in C just a couple of days ago, and I'm having trouble with this piece of my code:

while(!feof(fp)){
    fscanf(fp, "%04d\t%s\n", &code, students[ind].disc[0].name);
    if(code == dcode) return 1;
 }

code it's an inside fuction variable, and dcode is the course code to comparison, basicly, the function needs to compare if the course code inseerted exists, and then assign the course name to the .name element of the students structure. The file is opening correctly, and the it's structured in this way:

0101    Math
0102    History

and so...

can you guys help me?

inblank
  • 396
  • 1
  • 8
  • 26

1 Answers1

1

The dominating reason for having an infinite loop when you expect to make progress using fscanf alone is that fscanf does not read anything because of format mismatch.

In your case it appears that there is no \n on the final line, meaning that fscanf never matches it.

One way to fix this issue is to check the return value of fscanf instead of feof (it has its own problems, too, but that's a different topic)

while (fscanf(fp, "%04d\t%s", &code, students[ind].disc[0].name) == 2) {
    if(code == dcode) return 1;
    ind++; // You have probably forgotten about incrementing ind, right?
}

I removed '\n' character from the end of the format line because it is skipped over anyway.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523