C++ 寫檔,寫入txt文字檔各種範例

本篇 ShengYu 介紹 C++ 寫檔,寫入txt文字檔各種範例,上一篇介紹了 C++ 讀取文字檔,不熟練的話可以先複習一下,
以下 C++ 寫入文字檔的介紹內容將分為這幾部份,

  • C++ std::ofstream 寫入文字檔
  • C++ 將 C-Style 字元陣列的資料寫入文字檔
  • C++ 將 vector<string> 的資料寫入文字檔

C++ std::ofstream 寫入文字檔

這邊示範用 C++ std::ofstream 來寫入 txt 文字檔,不管是 char 陣列或 std::string 還是 int,甚至 float 跟 double 通通放進 ofstream 流不用錢(誤),通通放進 ofs 流會自動將這些變數進行轉換,

cpp-txt-write.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// g++ cpp-txt-write.cpp -o a.out
#include <iostream>
#include <fstream>
using namespace std;

int main() {
std::ofstream ofs;
int n = 123456;

ofs.open("output.txt");
if (!ofs.is_open()) {
cout << "Failed to open file.\n";
return 1; // EXIT_FAILURE
}

ofs << "Hello world " << n << "\n";
ofs << "This is a output text example\n";
ofs.close();
return 0;
}

執行起來會獲得這樣的執行結果,

1
2
Hello world 123456
This is a output text example

上述例子是用 ofstream::open() 開檔,當然你也可以使用 fstream::open(),然後在指定是 std::ios::out 就可以了,

1
2
3
std::fstream ofs;
ofs.open("output.txt", std::ios::out);
// ...

C++ 將 C-Style 字元陣列的資料寫入文字檔

這邊示範 C++ 將 C-Style 字元陣列的資料寫入文字檔裡,我們以學生姓名與學生分數為裡,總共有四名學生的資料,學生姓名存放在 char 陣列裡(name),學生分數放在 int 陣列裡(score),接著用迴圈去迭代將資料寫出,但要先計算出迭代次數,這邊使用 sizeof(score) / sizeof(int) 來計算出陣列大小,不可使用 sizeof(name) / sizeof(char) 去計算出大小,這意義不同。

接下來就看看完整程式怎麼寫,

cpp-txt-write2.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// g++ cpp-txt-write2.cpp -o a.out
#include <iostream>
#include <fstream>
using namespace std;

int main() {
std::ofstream ofs;
char name[4][256] = {"Alan", "John", "Tony", "Mary"};
int score[] = {75, 95, 60, 80};

ofs.open("output.txt");
if (!ofs.is_open()) {
cout << "Failed to open file.\n";
return 1; // EXIT_FAILURE
}

int size = sizeof(score) / sizeof(int);
for (int i = 0; i < 4; i++) {
ofs << name[i] << " " << score[i] << "\n";
}
ofs.close();
return 0;
}

結果輸出如下,

1
2
3
4
Alan 75
John 95
Tony 60
Mary 80

C++ 將 vector<string> 的資料寫入文字檔

這邊示範最常使用到的 std::vector 容器,將 std::vector 容器裡的元素(這邊示範 std::string) 寫入到文字檔裡,

cpp-txt-write3.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// g++ cpp-txt-write3.cpp -o a.out -std=c++11
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;

int main() {
std::ofstream ofs;
std::vector<std::string> str;
str.push_back("Hello world\n");
str.push_back("12345\n");
str.push_back("This is a output text example\n");

ofs.open("output.txt");
if (!ofs.is_open()) {
cout << "Failed to open file.\n";
return 1; // EXIT_FAILURE
}

for (auto &s : str) {
ofs << s;
}
ofs.close();
return 0;
}

結果輸出如下,

1
2
3
Hello world
12345
This is a output text example

以上就是 C++ 寫檔,寫入txt文字檔各種範例介紹,
如果你覺得我的文章寫得不錯、對你有幫助的話記得 Facebook 按讚支持一下!

其它相關文章推薦
C/C++ 新手入門教學懶人包
C/C++ 字串轉數字的4種方法
C++ virtual 的兩種用法
C/C++ 字串反轉 reverse
C/C++ call by value傳值, call by pointer傳址, call by reference傳參考 的差別
C++ 類別樣板 class template
std::sort 用法與範例
std::find 用法與範例
std::queue 用法與範例
std::map 用法與範例