Reputation: 27
I'm quite a beginner with C, and I'm just wondering why this 'for loop' isn't exiting:
int main()
{
FILE *openfile;
int notenumber;
openfile = fopen("test.txt", "w");
if (openfile == NULL)
{
printf("Error opening file\n");
}
else
{
for (notenumber=1; notenumber<=16; notenumber++)
{
notenumber = aserveGetNote();
fprintf(openfile, "Notenumber = %d\n", notenumber);
}
}
fclose(openfile);
return 0;
}
I don't understand why the loop will not exit. Even if I remove the if else loop and just have the for loop, I still have the same problem?
Upvotes: 0
Views: 106
Reputation: 1711
The question is already answered. One more hint: You do check after fopen
for NULL
. but what would happen if you do get a NULL
and call fclose
? On my machine I get a segmentation fault error.
Upvotes: 0
Reputation: 9817
notenumber = aserveGetNote();
: if aserveGetNote()
always returns something below 16, the for
loop can't be completed.
Try
for (notenumber=1; notenumber<=16; notenumber++)
{
int note = aserveGetNote();
fprintf(openfile, "Note = %d Notenumber %d\n", note,notenumber);
}
And follow the advice of @iharob : put fclose()
in the else
part of the test, to avoid calling fclose()
on NULL
.
Welcome to Stackoverflow !
Upvotes: 1
Reputation: 44906
aserveGetNote()
changes the value of notenumber
to something below 16, so the loop never exits as notenumber<=16;
is always true.
You can solve the problem by doing like this:
int test=aserveGetNote();
fprintf(openfile, "Notenumber = %d\n", test);
// or fprintf(openfile, "Notenumber = %d\n", notenumber); as I don't know which value do you want to store
Upvotes: 2