Reading integers from a file in C [duplicate]

2019-06-14 15:21发布

问题:

This question already has an answer here:

  • When should I use ampersand with scanf() 3 answers

I've been struggling with this for a really long time trying to figure it out, I'm guessing it's a really stupid noob mistake but I can't figure it out.

So I'm trying to read in an integer from a file and then do some operations in it, for the sake of the problem I'm just trying to output it here:

FILE * pFile;
int number;
pFile = fopen ("myfile.txt","r");
if (pFile!=NULL) {
fscanf(pFile, "%d", number);
fclose (pFile);
}
printf("number: %i", number);
return 0;

the contents of myfile.txt:

123

but when I run it it doesnt read it anything instead it says

RUN FAILED (exit value 1, total time: 32ms)

Thanks for any and all help

EDIT: I forgot to mention, it works as a string, it reads the correct number, but I can't do any operations on it, also if I set the number type to double it works but outputs some random number in the millions...

回答1:

You need to pass the address of the int variable to fscanf

fscanf(pFile, "%d", &number);


回答2:

You forgot to pass fscanf the address of number rather than the value of number. So replace

fscanf(pFile, "%d", number); 

with

fscanf(pFile, "%d", &number);

It is necessary to pass it the address of/ a pointer to number, because otherwise it cannot modify the contents of number.



回答3:

Yor need to have a pointer to number

i.e.

fscanf(pFile, "%d", &number);

And it is a good idea to check the return value from fscanf

You also probably need to do a flush.

i.e. After printf add the line

fflush(stdout);

Also you either need to initialise number or do a return if you are unable to open the file.

So in summary the code should look like this

FILE * pFile;
int number;
pFile = fopen ("myfile.txt","r");

if (NULL == pFile && 1 == fscanf(pFile, "%d", &number))
{
    printf("Number: %i", number);
    fflush(stdout);
    return 0;
}
else
{
    return -1;
}


回答4:

Never forget that for inputs (from keyboard/file) you need to mention the address of the variable. So you have to put & before the variable.

In your case:

fscanf(pFile, "%d", &number);

Also you'd better check if you reached the End-of-File or not:

while(fscanf(pFile, "%d", &number) != EOF){
    //do the logic
}

Check these manuals for more:

Linux Programmer's Manual

C library function - fscanf()



标签: c file scanf