文件读写

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中


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值