ofstream写入文件的几种方式

View Code
 1 #include <iostream>
 2 #include <string>
 3 #include <vector>
 4 #include <fstream>
 5 
 6 using namespace std;
 7 
 8 int main(int argc, char *argv[])
 9 {
10     int iArray[] = {23, 45, 57, 68, 23, 46, 68};
11     vector<int> iVec(iArray, iArray + sizeof(iArray) / sizeof(*iArray));
12 
13     ofstream ofs("test.txt");
14     if (!ofs)
15     {
16         cout << "File open error!" << endl;
17         exit(1);
18     }
19 
20     // (1)使用重载形式输入int型数据到文件中
21     for (size_t i = 0; i < iVec.size(); i++)
22     {
23         ofs << iVec[i] << " ";
24     }
25 
26     // (2)使用ofstream成员函数write()写入文件中
27     ofs.write("ZhuHai", strlen("ZhuHai"));
28 
29     // 关闭输出文件流
30     ofs.close();
31 
32     return 0;
33 }

文件test.txt的内容如下:

23 45 57 68 23 46 68 ZhuHai

原文地址:https://www.cnblogs.com/Robotke1/p/3037444.html