库函数方式访问文件

来源:互联网 发布:陈学冬郭敬明 知乎 编辑:程序博客网 时间:2024/05/17 23:36
#include <stdio.h>int main(int argc, char * argv[] ){FILE *stream;char bufwrite[30];char bufread[30];int i, numwrite, numread;/*写文件*/if( (stream = fopen( "fread.out", "w+" )) != NULL ){for(i=0; i<25; i++)bufwrite[i]=(char)('a'+i);numwrite = fwrite( bufwrite, sizeof(char), 25, stream );printf( "Write %d items\n", numwrite );fclose( stream );}elseprintf( "File could not be opened\n" );/*读文件*/if( (stream = fopen( "fread.out", "r+" )) != NULL ){ numread = fread( bufread, sizeof(char), 25, stream );printf( "Read %d items\n", numread );printf("Contents of buffer:\n");for(i=0; i<25; i++)printf("%c ", bufread[i]);printf("\n");fclose( stream );}elseprintf( "File could not be opened\n" );return 0;}


#include <stdio.h>int main( int argc, char * argv[] ){char s[81];long l;float fp;char c;FILE *stream;stream = fopen( "fscanf.out", "w+" );if( stream == NULL )printf( "The file fscanf.out was not opened\n" );else{/*写文件*/fprintf( stream, "%s %ld %f%c", "a-string", 65000, 3.14159, 'x' );/* Set pointer to beginning of file: */fseek( stream, 0L, SEEK_SET );/*读文件*/fscanf( stream, "%s", s );fscanf( stream, "%ld", &l );fscanf( stream, "%f", &fp );fscanf( stream, "%c", &c );printf( "%s\n", s );printf( "%ld\n", l );printf( "%f\n", fp );printf( "%c\n", c );fclose( stream );}return 0;}