C++Primer文件读写

#include<fstream>
#include<string>
#include<iostream>
#include<vector>
#include<iomanip>
using namespace std;

int main()
{
	//---------------------按行写文件-----------------------------
	//打开文件用于写,若文件不存在,则创建它,若已存在,则清空原内容
	//注意路径名中的斜杠要双写
	//	ofstream file("C:\\Users\\桑海\\Desktop\\HelloWord\\HelloWord.txt", ios::app);		//以app方式打开,在文件尾写入
	//作用同上
	string str;
	cout << "Enter the name of the file:" << endl;
	cin >> str;		//enter the name of the file you want to open
	ofstream file(str.c_str(), ios::app);		//open file named "str" for writing
	// check that the open succeeded
	if(!file)	//error: warn the user; bail out!
	{
		cerr << "error: unable to open input file: " << file << endl;
		return -1;
	}
	//string str;
	while(getline(cin, str))		//write
		file << setw(20) << str << endl;
	file.close();		//close file when we're done with it
	file.clear();
	//---------------------按行读文件-----------------------------
	ifstream file2("C:\\Users\\桑海\\Desktop\\HelloWord\\HelloWord.txt");
	while(!file2.eof())
	{
		getline(file2, str);
		cout << setw(20) << str << endl;
	}
	file2.close();		//close file when we're done with it
	file2.clear();		//reset state to ok
	return 0;
}

文件模式:
in 							打开文件做读操作(若文件不存在则创建,文件不存在则创建(ifstream默认的打开方式)
out 							打开文件做写操作(文件不存在则创建,若文件已存在则清空原内容,ofstream默认的打开方式)
app 						在每次写之前找到文件尾,即:总是在原文件尾写入操作(文件不存在则创建)
ate 							打开文件后立即将文件定位在文件尾,可改变定位位置
trunc 						打开文件时清空以存在的文件流
binary 						以二进制模式进行IO操作

打开文件的方法
调用构造函数时指定文件名和打开模式
ifstream f("d:\\12.txt",ios::nocreate);     //默认以 ios::in 的方式打开文件,文件不存在时操作失败
ofstream f("d:\\12.txt");            		//默认以 ios::out的方式打开文件
fstream f("d:\\12.dat",ios::in|ios::out|ios::binary); //以读写方式打开二进制文件

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值