FILE * fopen ( const char * filename, const char * mode );
int fclose( FILE * stream );
mode:r 只读;w 只写;a 只往末尾添加内容; r+ 既读又写;
FILE * fp = fopen( "c:\\data\\report.txt", "r" );
fscanf, fprintf
#include <stdio.h>
int main()
{
FILE * fp;
fp = fopen ( "d:\\students.txt", "r+" );
if ( fp == NULL )
{
printf( "Failed to open the file." );
return 1;
}
char szName[30], szGender[30];
int nId, nBirthYear, nBirthMonth, nBirthDay;
float fGPA;
while ( fscanf( fp,"%s%d%s%d%d%d%f", szName, &nId, szGender, &nBirthYear, &nBirthMonth, &nBirthDay, &fGPA ) != EOF )
{
printf( "%s%d%s%d%d%d%f\n", szName, nId, szGender, nBirthYear, nBirthMonth, nBirthDay, fGPA );
}
fprintf( fp, "%s %d %s %d %d %d %f\n", szName, nId, szGender, nBirthYear, nBirthMonth, nBirthDay, fGPA );
fclose( fp );
return 0;
}
fread, fwrite
必须是二进制打开:
FILE * fp = fopen( "d:\\students.dat", "rb" );
fread( & Stu, sizeof(Stu), 1, fp )
表示从文件中读取1个大小为sizeof(Stu)的数据块,写入到内存地址Stu中
fwrite( & Stu, sizeof(Stu), 1, fp2 )
表示从内存地址Stu读取1个大小为sizeof(Stu)的数据块,写入到到fp中