C++實(shí)現(xiàn)文本與二進(jìn)制文件讀寫操作的示例
在C++開發(fā)中,文件操作是必備技能之一。本文將全面解析C++文件讀寫的核心概念、操作方法和最佳實(shí)踐,包含豐富的代碼示例。
一、文件操作核心類
C++通過<fstream>頭文件提供三種核心類:
| 類名 | 功能描述 | 繼承關(guān)系 |
|---|---|---|
| ofstream | 文件輸出流(寫操作) | 繼承自ostream |
| ifstream | 文件輸入流(讀操作) | 繼承自istream |
| fstream | 文件輸入輸出流(讀寫操作) | 繼承自iostream |
二、文本文件操作
1. 寫入文本文件
#include <fstream>
#include <string>
int main() {
// 創(chuàng)建輸出流(默認(rèn)覆蓋模式)
std::ofstream outFile("data.txt");
if (!outFile) {
std::cerr << "文件創(chuàng)建失?。? << std::endl;
return 1;
}
// 寫入不同類型數(shù)據(jù)
outFile << "用戶日志\n";
outFile << "ID: " << 1001 << "\n";
outFile << "余額: $" << 2450.75 << "\n";
// 自動(dòng)關(guān)閉文件(RAII)
return 0;
}
2. 讀取文本文件
#include <fstream>
#include <iostream>
int main() {
std::ifstream inFile("data.txt");
if (!inFile.is_open()) {
std::cerr << "文件打開失敗!" << std::endl;
return 1;
}
// 逐行讀取
std::string line;
while (std::getline(inFile, line)) {
std::cout << line << std::endl;
}
// 重置讀取位置
inFile.clear();
inFile.seekg(0);
// 格式化讀取
int id;
double balance;
inFile.ignore(100, ':'); // 跳過"ID: "
inFile >> id;
inFile.ignore(100, '$'); // 跳過"余額: $"
inFile >> balance;
std::cout << "\n解析結(jié)果: ID=" << id
<< ", 余額=" << balance << std::endl;
return 0;
}
三、二進(jìn)制文件操作
1. 寫入二進(jìn)制數(shù)據(jù)
#include <fstream>
struct UserData {
int id;
double balance;
char name[32];
};
int main() {
UserData user = {1001, 2450.75, "張三"};
std::ofstream binFile("user.dat", std::ios::binary);
binFile.write(reinterpret_cast<char*>(&user), sizeof(user));
return 0;
}
2. 讀取二進(jìn)制數(shù)據(jù)
#include <fstream>
#include <iostream>
int main() {
std::ifstream binFile("user.dat", std::ios::binary);
if (!binFile) {
std::cerr << "二進(jìn)制文件打開失?。? << std::endl;
return 1;
}
UserData user;
binFile.read(reinterpret_cast<char*>(&user), sizeof(user));
std::cout << "用戶ID: " << user.id << "\n"
<< "姓名: " << user.name << "\n"
<< "余額: " << user.balance << std::endl;
return 0;
}
四、文件打開模式詳解
通過位或運(yùn)算符組合多種模式:
| 模式標(biāo)志 | 描述 |
|---|---|
| std::ios::in | 讀模式(默認(rèn)ifstream) |
| std::ios::out | 寫模式(默認(rèn)ofstream) |
| std::ios::app | 追加模式(不覆蓋原有內(nèi)容) |
| std::ios::ate | 打開后定位到文件末尾 |
| std::ios::trunc | 清空文件(默認(rèn)) |
| std::ios::binary | 二進(jìn)制模式 |
// 示例:以追加模式寫入文本
std::ofstream logFile("app.log",
std::ios::out | std::ios::app);
// 示例:讀寫二進(jìn)制文件(不截?cái)啵?
std::fstream dataFile("records.dat",
std::ios::binary |
std::ios::in |
std::ios::out);
五、錯(cuò)誤處理機(jī)制
健壯的文件操作必須包含錯(cuò)誤處理:
std::fstream file("critical.dat");
// 檢查文件狀態(tài)
if (file.fail()) {
std::cerr << "文件操作失??!" << std::endl;
}
// 詳細(xì)錯(cuò)誤診斷
if (!file) {
if (file.bad()) {
std::cerr << "不可恢復(fù)的錯(cuò)誤" << std::endl;
} else if (file.eof()) {
std::cerr << "到達(dá)文件末尾" << std::endl;
} else if (file.fail()) {
std::cerr << "非致命錯(cuò)誤(如格式錯(cuò)誤)" << std::endl;
}
}
六、最佳實(shí)踐與性能優(yōu)化
1. RAII管理資源
{
std::ofstream tmpFile("temp.txt");
// 文件在作用域結(jié)束時(shí)自動(dòng)關(guān)閉
}
2. 高效文件復(fù)制
bool copyFile(const std::string& src, const std::string& dst) {
std::ifstream in(src, std::ios::binary);
std::ofstream out(dst, std::ios::binary);
if (!in || !out) return false;
const size_t BUFFER_SIZE = 4096;
char buffer[BUFFER_SIZE];
while (in.read(buffer, BUFFER_SIZE)) {
out.write(buffer, BUFFER_SIZE);
}
out.write(buffer, in.gcount()); // 寫入剩余字節(jié)
return true;
}
3. C++17文件系統(tǒng)操作
#include <filesystem>
namespace fs = std::filesystem;
// 檢查文件存在
if (fs::exists("data.txt")) {
// 獲取文件大小
auto size = fs::file_size("data.txt");
// 重命名文件
fs::rename("old.txt", "new.txt");
}
七、應(yīng)用案例:日志系統(tǒng)
class Logger {
public:
Logger(const std::string& filename)
: logFile(filename, std::ios::app) {}
~Logger() { if (logFile) logFile.close(); }
void log(const std::string& message) {
if (!logFile) return;
auto now = std::chrono::system_clock::now();
auto time = std::chrono::system_clock::to_time_t(now);
logFile << std::put_time(std::localtime(&time), "%F %T")
<< " | " << message << "\n";
}
private:
std::ofstream logFile;
};
// 使用示例
Logger logger("app.log");
logger.log("系統(tǒng)啟動(dòng)");
logger.log("用戶登錄: ID=1001");
到此這篇關(guān)于C++實(shí)現(xiàn)文本與二進(jìn)制文件讀寫操作的示例的文章就介紹到這了,更多相關(guān)C++ 文本與二進(jìn)制文件讀寫操作內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C++11右值引用和std::move語句實(shí)例解析(推薦)
右值引用(及其支持的Move語意和完美轉(zhuǎn)發(fā))是C++0x將要加入的最重大語言特性之一。這篇文章主要介紹了C++11右值引用和std::move語句實(shí)例解析,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下2017-03-03
C++實(shí)現(xiàn)LeetCode(72.編輯距離)
這篇文章主要介紹了C++實(shí)現(xiàn)LeetCode(72.編輯距離),本篇文章通過簡(jiǎn)要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-07-07
C++有符號(hào)和無符號(hào)整數(shù)的位移操作過程
C++中位移操作對(duì)有符號(hào)與無符號(hào)整數(shù)處理不同:無符號(hào)左移補(bǔ)0,右移也補(bǔ)0;有符號(hào)右移補(bǔ)符號(hào)位(算術(shù)移位),左移可能觸發(fā)未定義行為,需注意類型轉(zhuǎn)換與跨平臺(tái)兼容性2025-09-09
C語言實(shí)現(xiàn)簡(jiǎn)單停車場(chǎng)管理系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了C語言實(shí)現(xiàn)簡(jiǎn)單停車場(chǎng)管理系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-12-12
C++一個(gè)數(shù)組賦值給另一個(gè)數(shù)組方式
文章介紹了三種在C++中將一個(gè)數(shù)組賦值給另一個(gè)數(shù)組的方法:使用循環(huán)逐個(gè)元素賦值、使用標(biāo)準(zhǔn)庫函數(shù)std::copy或std::memcpy以及使用標(biāo)準(zhǔn)庫容器,每種方法都有其適用的場(chǎng)景和注意事項(xiàng)2025-02-02

