1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int n, x, sum;
FILE* f = tmpfile();
if (!f)
{
fprintf( stderr, "Fooey! I could not create a temporary file!\n" );
return 1;
}
/* Create 10 random numbers */
srand( time( NULL ) );
for (n = 0; n < 10; n++)
{
fprintf( f, "%d\n", rand() % 100 );
}
/* Go back to the beginning of the file */
fseek( f, 0, SEEK_SET );
/* Read and display the numbers to the user */
for (n = 0; n < 10; n++)
{
fscanf( f, "%d", &x );
printf( "%d: %d\n", n, x );
}
/* Go back to the beginning of the file */
fseek( f, 0, SEEK_SET );
/* Read and sum the numbers */
sum = 0;
for (n = 0; n < 10; n++)
{
fscanf( f, "%d", &x );
sum += x;
}
printf( "sum = %d\n", sum );
/* All done: close and delete the temporary file */
fclose( f );
return 0;
}
|