Reputation: 11
How can I read from a file a number and after an array. i mean my file looks like that: 3 7 8 9
3 is the number of components, 7, 8 9 the other components of the array, arr[1], arr[2], arr[3].
Upvotes: 0
Views: 58
Reputation: 16540
one way to perform the desired functionality is:
First, open the file for reading:
FILE *fp = fopen( "filename.txt" );
Then check that the call to fopen()
was successful and handle any error:
if( ! fp )
{
perror( "fopen to read filename.txt failed" );
exit( EXIT_FAILURE );
}
Note: perror()
outputs both your error message and the text reason the system thinks the error occurred to stderr
. which is where error messages should be output.
reserve a variable to hold the count of following values:
int maxLoops;
then read the first number and use that number as the max iterations of a loop, of course, checking for errors
if( fscanf( fp, "%d", &maxLoops ) != 1 )
{
fprintf( stderr, "fscanf to read loop count failed\n" );
exit( EXIT_FAILURE );
}
Note: the scanf()
family of functions does not set errno
when some input format specifier
(in this case %d
) fails, so need to output an error message using something like fprinf()
.
Note: the scanf()
family of functions returns the number of successful input format conversions
(or EOF)
Note: exit()
and EXIT_FAILURE
are exposed via:
#include <stdlib.h>
then, reserve an array for the following entries in the file, using the Variable Array Length feature of C
int dataArray[ maxLoops ];
Now, set up the loop that will read the rest of the data
for( int i = 0; i < maxLoops; i++ )
{
for each pass through the loop read another entry into the array, of course, checking for errors
if( fscanf( fp, "%d", &dataArray[i] ) != 1 )
{
fprintf( stderr, "fscanf for data value failed\n" );
exit( EXIT_FAILURE );
}
} // end the loop
then, cleanup before doing anything else:
fclose( fp );
What you do with the data is up to you. You might want to print out each of the data values with a loop, similar to:
for( int i = 0; i < maxLoops; i++ )
{
printf( "entry %d = %d\n", i, dataArray[i] );
}
Note: when calling printf()
no need to obtain the address of a variable (unless that is what you want to print). However, when inputting a variable, as when calling fscanf()
need the address of the variable.
Upvotes: 1