在编写C++程序时,cout
和cin
是最常用的写入和输出操作,但只限于在终端上的操作,不太严谨;实际应用中,我们常常会用到比如要输出一段数据到某个文件中(最简单的就是到txt
中),或者打印日志,这种情况下,就需要用到文件读写操作了。
下面是文件读写操作的简单示例应用。
将数据写入文件需要加入fstream
这个头文件,然后定义ofstream
对象,用起来的话就跟cout差不多,不同的就是需要有一个open
和close
的操作。
// c++写数据到文件中
#include <iostream>
#include <vector>
#include <fstream>
using namespace std;
#define num 3
int main()
{
ofstream write;
write.open("test.txt",ios::app);
vector<string> vec(num);
vec[0] = "hello";
vec[1] = "world";
vec[2] = '!';
for(int i = 0; i < num; i++)
{
write << vec[i];
write << endl;
}
write.close();
cout << "文件写入完成\n";
return 0;
}
读取数据也是用到fstream
这个头文件,定义ifstream
对象,这里只需要执行open
操作即可,然后用getline
去读取数据。
// c++从文件中读取数据
#include <iostream>
#include <vector>
#include <fstream>
using namespace std;
int main()
{
ifstream read;
read.open("test.txt", ios::in);
if (!read.is_open())
{
cout << "读取文件失败" << endl;
return 0;
}
string buf;
while (getline(read,buf))
{
cout << buf << endl;
}
return 0;
}