c++文件操作可以使用库"fstream"来解决
它有 3 个很重要的类。
ifstream
ofstream
fstream
ifstream 是针对文件读取的流
ofstream 是针对文件写入的流
fstream 针对文件读取和写入的流
打开文件
void open(const std::string& __s, ios_base::openmode __mode );
open 有 2 个参数,第一个参数代表要打开的文件的地址。
第二个参数代表操作文件的模式。(下面给出具体)
模式标志 | 描述 |
---|---|
ios::app | 追加模式,所有写入的数据都追加到文件末尾 |
ios::ate | 文件打开以后定义到文件末尾 |
ios::in | 打开文件用于读取 |
ios::out | 打开文件用于写入(若文件已存在,清除之前所有内容) |
ios::trunc | 若该文件存在,其内容在打开文件前被截断,即把文件长度设为0。(移除原文件内容,不存在时不会自创文件) |
例子
例1:
(读取文档,每行为一个保存在容器中,再用迭代器输出)
#include<iostream>
#include<vector>
#include<string>
#include<fstream>
using namespace std;
int main(void)
{
ifstream in("data");//打开文件
if (!in)
{
cerr << "无法打开输入文件!" << endl;
return -1;
}
string line;
vector<string> words;
while (getline(in, line))//从文件中读取一行
{
words.push_back(line);//添加到vector中
}
in.close();//输入完毕,关闭文件
vector<string>::const_iterator it = words.begin();//迭代器
while (it != words.end()) //遍历输出vector中的元素
{
cout << *it << endl;
++it;
}
//return 0;
system("pause");
}
例2:
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
fstream fd;
fd.open("123.txt",ios::app);
fd<<"满堂花醉三千客 无人"<<endl;
fd<<"一剑霜寒十四州";
fd<<"zzq";
fd.close();
ifstream in;//读取文件
in.open("123.txt",ios::in);
string s="1",t="2";//string变量,遇到空格和换行会截止
getline(in,t);
in>>s;
cout<<s<<endl;
cout<<t;
in.close();
return 0;
}