#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); //以读写方式打开二进制文件