Reputation: 11
Hello i got a problem im trying to solve problem and learn how the learning from files works .I did this code by tutorial and when i execute instead of learning my file and write on console something like 1 4 6 5 1 etc.. its just spam only 0 0 0 0 0 0 0 and then repeat If you would say me where is the problem it will be good thanks for ur time :)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define UNUSED(__ARG__) ((void)__ARG__)
int main(int argc, char** argv)
{
UNUSED(argc);
UNUSED(argv);
int i = 0;
FILE* x =fopen("cisla.txt","r");
fscanf(x,"%d",&i);
while (!feof (x))
{
printf("%d",i);
fscanf(x,"%d",&i);
}
fclose(x);
return 0;
}
Upvotes: 0
Views: 763
Reputation: 165416
Whatever tutorial this is, throw it out.
First, you need to check whether your file operations succeeded, otherwise the program will blindly continue along. Likely the fopen
failed. It returns NULL
on failure so you can check for that and get an error message with perror
.
FILE *x = fopen("cisla.txt","r");
if( x == NULL ) {
perror("Could not open the file");
exit(1);
}
Then, as others have mentioned, you don't check for end of file. Instead do the IO operation and check whether it succeeded or failed. In this case, fscanf
returns the number of matched items which should be 1.
while ( fscanf(x, "%d", &i) == 1 ) {
printf("%d",i);
}
Note that the scanf
family is fraught with gotchas. But you'll get to them later.
Finally, that UNUSED
stuff is very clever and totally unnecessary. Just declare main
with no arguments. This is perfectly valid.
int main() {
Upvotes: 4