文件读写!

#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;
}


猜你喜欢

转载自blog.csdn.net/qq_42972267/article/details/85856200