在C++中,文本文件的讀寫(xiě)可以使用標(biāo)準(zhǔn)庫(kù)中的fstream類。fstream類提供了與文件的輸入和輸出操作相關(guān)的成員函數(shù)和操作符重載。
以下是一些常用的文本文件讀寫(xiě)操作方法:
#include <fstream>
using namespace std;
int main() {
ofstream file;
file.open("example.txt"); // 打開(kāi)文件example.txt
// 或者
// ofstream file("example.txt");
// 寫(xiě)入操作...
file.close(); // 關(guān)閉文件
return 0;
}
#include <fstream>
using namespace std;
int main() {
ofstream file("example.txt");
if (file.is_open()) {
file << "Hello, World!" << endl;
file << "This is a text file." << endl;
file.close();
}
return 0;
}
#include <fstream>
#include <iostream>
using namespace std;
int main() {
ifstream file("example.txt");
if (file.is_open()) {
string line;
while (getline(file, line)) {
cout << line << endl;
}
file.close();
}
return 0;
}
以上是一些基礎(chǔ)的文本文件的讀寫(xiě)方法,你可以根據(jù)需要進(jìn)一步探索fstream類提供的其他成員函數(shù)和操作符重載。