69,369
社区成员
发帖
与我相关
我的任务
分享
/* 将 1 - 100 写入文件 然后倒序读出来 */
#include <stdio.h>
#include <stdlib.h>
int main( void )
{
FILE* pfile = NULL;
int val = 0;
long cnt = 0L;
int i = 0;
// open the file
pfile = fopen( "abc.txt" , "w" );
if( !pfile )
{
fprintf( stderr , "can not open the file \n" );
exit( 1 );
}
// write the file
for( val = 1 ; val <= 100 ; ++ val )
{
fwrite( &val , sizeof( int ) , 1 , pfile );
}
// close the file
fclose( pfile );
// open the file
pfile = fopen( "abc.txt" , "r" );
for( i = 1 ; i <= 100 ; ++ i )
{
fseek( pfile , - i * sizeof( int ) , SEEK_END );
fread( &val , sizeof( int ) , 1 , pfile );
printf( "%d " , val );
if( i % 10 == 0 ) printf( "\n" );
}
// close the file
fclose( pfile );
return 0;
}
100 99 98 97 96 95 94 93 92 91
90 89 88 87 86 85 84 83 82 81
80 79 78 77 76 75 74 73 72 71
70 69 68 67 66 65 64 63 62 61
60 59 58 57 56 55 54 53 52 51
50 49 48 47 46 45 44 43 42 41
40 39 38 37 36 35 34 33 32 31
30 29 28 27 26 25 24 23 22 21
20 19 18 17 16 15 14 13 12 11
10 9 8 7 6 5 4 3 2 1
/* 将 1 - 100 写入文件 然后倒序读出来 */
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE* pfile = NULL;
int val = 0;
long cnt = 0L;
int i = 0;
// open the file
//pfile = fopen("abc.txt", "w");
pfile = fopen("1.txt", "wb");
if (!pfile)
{
fprintf(stderr, "can not open the file \n");
exit(1);
}
// write the file
for (val = 1; val <= 100; ++val)
{
fwrite(&val, sizeof(int), 1, pfile);
}
// close the file
fclose(pfile);
// open the file
pfile = fopen("1.txt", "rb");
for (i = 1; i <= 100; ++i)
{
fseek(pfile, -i * sizeof(int), SEEK_END);
fread(&val, sizeof(int), 1, pfile);
printf("%d ", val);
if (i % 10 == 0) printf("\n");
}
// close the file
fclose(pfile);
return 0;
}