文件读写!

#include <iostream>
#include <fstream>
#include <string>
using std::ofstream;
using std::endl;
using std::ifstream;
using std::cout;
using std::ios;
int main1()              //一次读一个
{
	ofstream ofs;
	ofs.open("aaa.txt");
	if (!ofs)
		exit(-1);
	for (char i = 'a';i < 'z';i++)
		ofs << i;       //第一种方法
	ofs.close();

	ifstream ifs;
	ifs.open("aaa.txt");
	if (!ifs)
		exit(-1);
	char ch;
	while (ifs >> ch)
	{
		cout << ch;
	}
	ifs.close();
	system("pause");
	return 0;
}
int main1()               //一次读一个
{
	ofstream fs;
	fs.open("aaa.txt");
	if (!fs)
		exit(-1);
	for (char i = 'a';i < 'z';i++)
		fs.put(i);		 //第二种方法
	fs.close();

	ifstream ifs;
	ifs.open("aaa.txt");
	if (!ifs)
		exit(-1);
	char ch;
	while (ifs.get(ch))
	{
		cout << ch;
	}
	ifs.close();
	system("pause");
	return 0;
}


int main2()//一次读写一行
{
	ofstream ofs;
	ofs.open("aaa.txt");
	if (!ofs)
		exit(-1);
	ofs << "aaaaaaa" << endl;
	ofs << "bbbbbbbb" << endl;
	ofs << "cccccccc" << endl;
	ofs.close();

	ifstream ifs;
	ifs.open("aaa.txt");
	if (!ifs)
		exit(-1);
	char buf[1024];
	while (ifs.getline(buf, 1024)) // while(ifs>>buf)
	{
		cout << buf << endl;       // 需手动添加换行
	}
	ifs.close();
	system("pause");
	return 0;
}


struct Student
{
	char _name[30];
	char _sex;
	int _age;
	double _score;
};

int main3()           //读写结构体
{
	Student stu[4] =
	{
		{"wang",'x',25,99},
		{"han",'x',24,98 },
		{"ying",'y',30,100},
		{"huan",'y',55,97 }
	};
	ofstream ofs;
	ofs.open("aaa.txt",ios::out|ios::trunc|ios::binary);
	if (!ofs)
		exit(-1);
	ofs.write((char *)&stu, sizeof(stu));
	ofs.close();
	
	Student s;
	ifstream ifs;
	ifs.open("aaa.txt",ios::in|ios::binary);
	if (!ifs)
		exit(-1);
	//ifs.seekg(sizeof(s), ios::beg);
	while (ifs.read((char *)&s, sizeof(s)),!ifs.eof())
	{
		cout << s._name << endl;
		cout << s._age << endl;
		cout << s._score << endl;
		cout << s._sex << endl;
	}
	ifs.close();
	system("pause");
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值