官网手册
c++文件流操作
http://www.cplusplus.com/reference/fstream/fstream/
一个简单的代码
#include <fstream>
using namespace std;
int main () {
fstream fs;
fs.open ("test.txt", fstream::in | fstream::out | fstream::app);
fs << " more lorem ipsum";
fs.close();
return 0;
}
打开方式
成员变量 | 全称 | 说明 |
---|---|---|
in | input | 读 |
out | output | 写 |
binary | binary | 二进制文件操作 |
ate | at end | 返回文件尾端的位置 |
app | append | 从文件末尾追加内容 |
trunc | truncate | 销毁源文件,然后新建打开 |
以上操作,可以通过运算符(|),来结合使用
in
如果文件创建过,则成功打开;否则,找不到文件
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
fstream file;
file.open("2.txt", fstream::in);
if (file.is_open())
{
cout << "打开文件" << endl;
file.write("hellow", 6); // 无法写入文件
}
else
cout << "没有创建文件" << endl;
file.close();
cin.get();
return 0;
}
out
如果文件不存在,先创建,再写入;如果文件存在,直接覆盖原来内容
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
fstream file;
file.open("1.txt", fstream::out);
if (file.is_open())
{
cout << "创建并打开文件" << endl;
file.write("hellow", 6);
}
else
cout << "out 模式不能创建文件" << endl;
file.close();
cin.get();
return 0;
}
(未完待续……)