Guys, OP is newbie who has been given assignment to work with a function that is confusing to begin with.
@
azioupos
There are several things to think about.
1) A function (like
fscanf()) returns a value. What that value is depends on the function. In
fscanf()'s case, it returns the number of
things successfully read from file.
2) A function may have
input arguments. These are things you pass to the function to tell it what to do. In this case, the first argument is the file to manipulate (a
FILE* obtained from something like
fopen()).
The second argument is a list of the things you want to read from the file. In your case, you want to read an integer, so you tell it by saying
"%d" (or
"%i").
3) A function may have
output arguments. These are things that the function will modify. The
&x is the output argument.
fscanf() will put the integer it reads from the file into the integer variable named 'x'.
So:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
FILE* f; /* This is the variable we'll use to access a file. */
int x; /* This is the variable that will hold the value we will read from the file. */
int n; /* This is the variable that will hold the number of items read from the file. */
f = fopen( "fooey.txt", "r" ); /* Associate f with the file "fooey.txt" */
if (f == NULL) /* Make sure to check that the file could be opened */
{
puts( "Hey, I could not open the file \"fooey.txt\"" );
return 1;
}
n = fscanf( f, "%d", &x ); /* Attempt to read an integer from the file and put its value in x. */
/* n now has a value of 0 if no integer could be read from the file; */
/* n has a value of 1 if an integer was successfully read from the file. */
if (n != 0)
{
printf( "%s %d\n", "Yay, the integer read from the file was ", x );
}
else
{
puts( "The file did not have an integer as the first thing in the file." );
}
|
Hope this helps.
[edit] Oh yeah, don't forget to look at the documentation for
fscanf()
http://www.cplusplus.com/reference/cstdio/fscanf/?kw=fscanf