C++文件操作1

本文详细介绍了C++中的流操作,包括标准输入输出流iostream、文件流fstream的使用方法及其实现技巧。通过实例展示了如何利用istream和ostream进行数据交换,并深入探讨了fstream的文件读写操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

2018/5/31

1.iostream

1.在C++中作为标准库存在,在其中含有着istream(输入流)和ostream(输出流),相当于两个内置的类,同时,我们使用的cin,cout相当于类中的对象;

注:可以对<<和>>进行重载,从而实现直接输出对象名直接输出内部内容的效果

#include<iostream>//含有istream和ostream
using namespace std;
class Passage
{
private:
	int p_num1, p_num2;
public:
	Passage()
	{
		p_num1 = 0;
		p_num2 = 0;
	}
	Passage(int num1,int num2)
	{
		p_num1 = num1;
		p_num2 = num2;
	}
	//运算符重载(friend)
	friend ostream &operator<<(ostream&output, const Passage&number)
	{
		output << "num1 is " << number.p_num1 << endl;
		output << "num2 is " << number.p_num2 << endl;
		return output;//返回对象
	}
	friend istream&operator>>(istream&input, Passage&number)
	{
		input >> number.p_num1 >> number.p_num2;
		return input;
	}
};
int main()
{
	Passage p1(10, 20), p2(20, 30), p3;
	cout << "Enter the value of object : " << endl;
	cin >> p3;
	cout << "first one\n" << p1 << endl;
	cout << "second one\n" << p2 << endl;
	cout << "third one\n" << p3 << endl;
	system("pause");
}

2.fstream

1.在C++中作为另外一个标准库而存在

2.内部有ifstream和ofstream(相当于两个类)

<1>:ifstream:表示输入文件流,用于从文件中读取信息(只读操作)

<2>:ofstream:表示输出文件流,用于向文件中写入操作

3.open()函数

void open(const char *filename, ios::openmode mode);

注:成员第一参数为文件名,第二参数为模式选择

ios::app(追加)所有写入追加到文件的末尾

ios::ate:读取位置定位到文件的末尾

ios::in:用于读取(类为ifstream则可以忽略)

ios::out:用于写入(类为ofstream则可以忽略)

ios::trunc:如果该文件存在,则截断文件;

4.close()函数

C++文件终止后,自动关闭所有刷新流,释放所有的内存,关闭所有文件

注:

在程序的最后记得使用close(),释放内存

5.写入和读取文件

//fstream
//ifstream 读取 ios::in
//ofstream 写入 ios::out
//fstream 写入和读取 ios::in||ios::out
//默认格式可以不写
//getchar用于获取换行符号

#include<iostream>
#include<fstream>
using namespace std;
int main()
{
	char data[100];
	//写模式
	ofstream outfile;
	outfile.open("afile.txt");
	//控制台操作
	cout << "Writing to the file" << endl;
	cout << "enter your name" << endl;
	cin.getline(data, 100);//输出100个字符以内 回车截止
	
	outfile << data << endl;

	cout << "Enter your age" << endl;
	cin >> data;
	cin.ignore();//忽略多余成分
	outfile << data << endl;//向文件中写入
	outfile.close();
	//读模式
	ifstream infile;
	infile.open("afile.txt");
	cout << "Reading" << endl;
	infile >> data;
	cout << data << endl;
	infile >> data;
	cout << data << endl;
	infile.close();

	system("pause");
	

}







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值