C++通過(guò)ofstream和ifstream實(shí)現(xiàn)文件讀寫(xiě)
一、簡(jiǎn)介
C++文件流是用于進(jìn)行文件讀寫(xiě)操作的工具,它提供了一種能夠簡(jiǎn)單、高效地與外部文件進(jìn)行交互的方式。C++中文件流主要通過(guò)ofstream和ifstream來(lái)實(shí)現(xiàn)對(duì)文件的寫(xiě)入和讀取。
- ofstream(output file stream)用于寫(xiě)入文件,可以創(chuàng)建、打開(kāi)并寫(xiě)入文件內(nèi)容。
- ifstream(input file stream)用于讀取文件內(nèi)容,可以打開(kāi)并讀取文件中的數(shù)據(jù)。
文件流操作可以是文本模式的,也可以是二進(jìn)制模式的,允許以不同的方式對(duì)文件進(jìn)行讀取和寫(xiě)入。
C++文件流提供了許多用于處理文件的功能和方法,包括打開(kāi)文件、讀寫(xiě)文件內(nèi)容、關(guān)閉文件等。為了保證文件流的正確使用,需要對(duì)文件操作過(guò)程中可能出現(xiàn)的錯(cuò)誤進(jìn)行處理。
二、開(kāi)始使用ofstream進(jìn)行文件寫(xiě)入
創(chuàng)建一個(gè)ofstream對(duì)象來(lái)打開(kāi)和寫(xiě)入文件:
包含必要的頭文件:
#include <fstream>
創(chuàng)建ofstream對(duì)象:
std::ofstream outputFile;
打開(kāi)文件并寫(xiě)入內(nèi)容:
outputFile.open("example.txt"); // 打開(kāi)名為example.txt的文件進(jìn)行寫(xiě)入 if (outputFile.is_open()) { outputFile << "Hello, World!" << std::endl; // 將字符串寫(xiě)入文件 outputFile << "This is a sample text." << std::endl; } else { std::cout << "Failed to open the file." << std::endl; // 如果文件打開(kāi)失敗,輸出錯(cuò)誤信息 } outputFile.close(); // 關(guān)閉文件流
在文件成功打開(kāi)后,可以使用流插入運(yùn)算符(<<)來(lái)向文件中寫(xiě)入內(nèi)容。最后,記得使用close()函數(shù)關(guān)閉文件流,釋放資源并確保文件操作的完成。這樣就完成了創(chuàng)建ofstream對(duì)象并進(jìn)行文件寫(xiě)入的操作。
下面是ofstream類的主要成員函數(shù):
成員函數(shù) | 描述 | 參數(shù) |
---|---|---|
open() | 打開(kāi)文件 | const char* filename, ios_base::openmode mode |
close() | 關(guān)閉文件 | 無(wú) |
is_open() | 檢查文件是否已經(jīng)成功打開(kāi) | 無(wú) |
good() | 檢查文件流是否處于一個(gè)有效狀態(tài) | 無(wú) |
bad() | 檢查文件流是否處于一個(gè)錯(cuò)誤狀態(tài) | 無(wú) |
operator<< | 將數(shù)據(jù)寫(xiě)入到文件流中 | int, char, string等不同類型的數(shù)據(jù) |
tellp() | 返回當(dāng)前文件指針的位置(寫(xiě)入位置) | 無(wú) |
seekp() | 設(shè)置寫(xiě)入位置 | streamoff off, ios_base::seekdir way |
flush() | 刷新輸出緩沖區(qū) | 無(wú) |
rdbuf() | 獲取緩沖區(qū)指針 | 無(wú) |
其中,ios_base::openmode是一個(gè)枚舉類型,用于指定文件打開(kāi)模式,包括out(寫(xiě)入)、app(追加)、trunc(截?cái)嗖?xiě)入)、ate(打開(kāi)文件后立即定位到文件末尾)。
除了上述成員函數(shù)外,ofstream還可以使用繼承自ostream的其他成員函數(shù),包括setf、unsetf、width 等用于設(shè)置標(biāo)志和格式控制。
ofstream 類是用于將數(shù)據(jù)寫(xiě)入文件的輸出流類。它繼承自ostream類,因此具有ostream類的所有成員函數(shù),同時(shí)也具有一些自己特有的成員函數(shù)。
open():打開(kāi)文件,參數(shù)包括文件名和打開(kāi)模式。
ofstream outputFile; outputFile.open("example.txt");
close():關(guān)閉打開(kāi)的文件。
outputFile.close();
is_open():檢查文件是否成功打開(kāi)。
if (outputFile.is_open()) { // 文件已經(jīng)成功打開(kāi) } else { // 文件打開(kāi)失敗 }
good():檢查文件流是否處于一個(gè)有效狀態(tài)。
if (outputFile.good()) { // 文件流處于有效狀態(tài) } else { // 文件流不處于有效狀態(tài) }
bad():檢查文件流是否處于一個(gè)錯(cuò)誤狀態(tài)。
if (outputFile.bad()) { // 文件流處于錯(cuò)誤狀態(tài) } else { // 文件流未處于錯(cuò)誤狀態(tài) }
三、使用ifstream進(jìn)行文件讀取
創(chuàng)建一個(gè)ifstream對(duì)象來(lái)打開(kāi)和讀取文件:
- 包含必要的頭文件:
#include <fstream>
- 創(chuàng)建ifstream對(duì)象:
std::ifstream inputFile;
- 打開(kāi)文件并讀取內(nèi)容:
inputFile.open("example.txt"); // 打開(kāi)名為example.txt的文件進(jìn)行讀取 if (inputFile.is_open()) { std::string line; while (std::getline(inputFile, line)) { std::cout << line << std::endl; // 輸出文件中的每一行內(nèi)容 } } else { std::cout << "Failed to open the file." << std::endl; // 如果文件無(wú)法打開(kāi),輸出錯(cuò)誤信息 } inputFile.close(); // 關(guān)閉文件流
通過(guò)循環(huán)使用getline()函數(shù)逐行讀取文件內(nèi)容,并輸出到控制臺(tái)上。最后,別忘了使用close()函數(shù)關(guān)閉文件流,以確保讀取完成。
下面是ifstream類的主要成員函數(shù)以及它們的描述和參數(shù):
成員函數(shù) | 描述 | 參數(shù) |
---|---|---|
open() | 打開(kāi)文件 | const char* filename, ios_base::openmode mode |
close() | 關(guān)閉文件 | 無(wú) |
is_open() | 檢查文件是否已經(jīng)成功打開(kāi) | 無(wú) |
good() | 檢查文件流是否處于一個(gè)有效狀態(tài) | 無(wú) |
bad() | 檢查文件流是否處于一個(gè)錯(cuò)誤狀態(tài) | 無(wú) |
operator>> | 從文件流中讀取數(shù)據(jù) | int, char, string等不同類型的數(shù)據(jù) |
tellg() | 返回當(dāng)前文件指針的位置(讀取位置) | 無(wú) |
seekg() | 設(shè)置讀取位置 | streamoff off, ios_base::seekdir way |
peek() | 查看下一個(gè)字符,但不提取它 | 無(wú) |
ignore() | 忽略一定數(shù)量的字符 | streamsize n = 1, int_type delim = Traits::eof() |
其中,ios_base::openmode 是一個(gè)枚舉類型,用于指定文件打開(kāi)模式,包括 in(讀?。?、binary(二進(jìn)制模式)等。
四、文件的打開(kāi)模式
模式 | 描述 |
---|---|
in | 以輸入方式打開(kāi)文件,允許讀取文件內(nèi)容。 |
out | 以輸出方式打開(kāi)文件,允許寫(xiě)入文件內(nèi)容。如果文件不存在,則創(chuàng)建新文件;如果文件已存在,則將其長(zhǎng)度截為0。 |
app | 在文件末尾附加內(nèi)容,允許寫(xiě)入文件;如果文件不存在,則創(chuàng)建新文件。 |
ate | 打開(kāi)文件后立即定位到文件末尾。 |
trunc | 如果文件已存在,則將截?cái)辔募L(zhǎng)度為0(清空文件)。 |
binary | 以二進(jìn)制方式打開(kāi)文件,而非文本模式。文件內(nèi)容將以二進(jìn)制格式進(jìn)行讀取和寫(xiě)入,而不是以文本格式。 |
通過(guò)組合不同的打開(kāi)模式選項(xiàng),可以實(shí)現(xiàn)對(duì)文件的不同方式打開(kāi),包括讀取、寫(xiě)入、追加和二進(jìn)制模式的操作。
不同場(chǎng)景下選擇打開(kāi)模式的方法:
讀取文件:
- 如果只需要讀取文件的內(nèi)容,應(yīng)該選擇“in”模式,以輸入方式打開(kāi)文件。
- 如果希望以二進(jìn)制方式讀取文件內(nèi)容,可以選擇“
in | binary
”模式。
寫(xiě)入文件:
- 如果希望創(chuàng)建新文件并寫(xiě)入內(nèi)容,應(yīng)該選擇“out”模式,以輸出方式打開(kāi)文件。
- 如果文件已存在,且希望覆蓋原有內(nèi)容,可以選擇“out”模式。
- 如果希望在文件末尾追加內(nèi)容,可以選擇“app”模式。
二進(jìn)制文件操作:
- 如果需要以二進(jìn)制方式對(duì)文件進(jìn)行讀寫(xiě),應(yīng)該選擇“binary”模式。
- 當(dāng)進(jìn)行二進(jìn)制文件操作時(shí),可以考慮使用“
in | binary
”或“out | binary
”模式,具體取決于是讀取還是寫(xiě)入操作。
確保文件安全性:
- 如果需要在寫(xiě)入文件內(nèi)容之前清空文件內(nèi)容,可以選擇“out | trunc”模式,以確保在寫(xiě)入之前文件已被清空。
- 在追加內(nèi)容之前,可以選擇“app”模式,以確保在文件末尾追加內(nèi)容。
五、錯(cuò)誤處理
5.1、處理文件打開(kāi)和讀寫(xiě)過(guò)程中可能發(fā)生的錯(cuò)誤
通過(guò)檢查文件流的狀態(tài)以及使用異常處理來(lái)處理文件打開(kāi)和讀寫(xiě)過(guò)程中可能發(fā)生的錯(cuò)誤。
檢查流的狀態(tài):在打開(kāi)文件或進(jìn)行讀寫(xiě)操作之后,使用流的成員函數(shù)來(lái)檢查文件流的狀態(tài)。常用的函數(shù)包括good()、bad()、fail()和eof()等。通過(guò)檢查這些狀態(tài)來(lái)確定文件操作是否成功,并根據(jù)需要采取相應(yīng)的操作。
使用異常處理:C++的異常處理機(jī)制可以用于捕獲和處理文件操作中的錯(cuò)誤。通過(guò)在文件操作代碼塊中使用try-catch語(yǔ)句,可以捕獲可能發(fā)生的異常,例如文件打開(kāi)失敗、讀寫(xiě)錯(cuò)誤等,并進(jìn)行相應(yīng)的處理或報(bào)告錯(cuò)誤信息。
示例:
#include <iostream> #include <fstream> int main() { std::ofstream outputFile("example.txt"); try { if (!outputFile) { throw "File opening failed."; } outputFile << "Hello, World!"; if (outputFile.fail()) { throw "Writing to file failed."; } outputFile.close(); } catch (const char* errorMessage) { std::cerr << "Error: " << errorMessage << std::endl; } return 0; }
通過(guò)檢查文件流的狀態(tài)和使用異常處理,可以有效地處理文件打開(kāi)和讀寫(xiě)過(guò)程中可能發(fā)生的錯(cuò)誤,從而確保文件操作的穩(wěn)定性和安全性。
5.2、使用流的狀態(tài)來(lái)檢測(cè)和處理錯(cuò)誤
C++的流類提供了幾個(gè)成員函數(shù)來(lái)獲取流的狀態(tài),并且可以通過(guò)這些狀態(tài)來(lái)檢測(cè)和處理錯(cuò)誤。這些狀態(tài)標(biāo)志通常以成員函數(shù)的返回值形式表示。
用于檢測(cè)和處理流狀態(tài)的成員函數(shù):
good():檢查流是否處于有效狀態(tài),即未發(fā)生任何錯(cuò)誤。返回true表示流處于有效狀態(tài)。
bad():檢查流是否處于錯(cuò)誤狀態(tài)。返回true表示流處于錯(cuò)誤狀態(tài)。
fail():檢查流是否處于失敗狀態(tài),可能是由于輸入/輸出操作失敗,但并非致命錯(cuò)誤。返回true表示流處于失敗狀態(tài)。
eof():檢查是否已經(jīng)達(dá)到文件的末尾(end-of-file)。返回true表示已經(jīng)達(dá)到文件末尾。
這些狀態(tài)標(biāo)志可以幫助我們確定文件讀寫(xiě)過(guò)程中出現(xiàn)的具體錯(cuò)誤,并做出相應(yīng)的處理。例如,在讀取文件時(shí),可以檢查eof()狀態(tài)來(lái)確定是否已經(jīng)讀到文件末尾;在寫(xiě)入文件時(shí),可以檢查fail()狀態(tài)來(lái)確定是否寫(xiě)入失敗等。
示例:
#include <iostream> #include <fstream> int main() { std::ifstream inputFile("example.txt"); if (!inputFile.good()) { std::cerr << "Error: Failed to open the file." << std::endl; return 1; } std::string data; while (inputFile >> data) { if (inputFile.fail()) { std::cerr << "Error: Failed to read from the file." << std::endl; break; } std::cout << data << " "; } inputFile.close(); if (inputFile.bad()) { std::cerr << "Error: An unrecoverable error occurred while reading the file." << std::endl; return 1; } return 0; }
六、二進(jìn)制文件操作
使用二進(jìn)制模式來(lái)讀寫(xiě)文件在C++中是很常見(jiàn)的。二進(jìn)制模式適用于處理非文本文件,如圖像、音頻、視頻等內(nèi)容。在二進(jìn)制模式下,文件的內(nèi)容以其原始的字節(jié)形式進(jìn)行讀寫(xiě),而不會(huì)對(duì)內(nèi)容進(jìn)行解釋或轉(zhuǎn)換。
- 以二進(jìn)制模式打開(kāi)文件:使用 ofstream 或 ifstream 對(duì)象,并在 open() 函數(shù)中指定 binary 模式。
std::ofstream outputFile("example.bin", std::ios::out | std::ios::binary); std::ifstream inputFile("example.bin", std::ios::in | std::ios::binary);
- 寫(xiě)入數(shù)據(jù)到二進(jìn)制文件:使用 write() 函數(shù)向文件中寫(xiě)入二進(jìn)制數(shù)據(jù)。write() 函數(shù)的參數(shù)包括一個(gè)指向要寫(xiě)入的數(shù)據(jù)的指針和數(shù)據(jù)的長(zhǎng)度。
int data[] = {1, 2, 3, 4, 5}; outputFile.write(reinterpret_cast<char*>(&data), sizeof(data));
- 從二進(jìn)制文件中讀取數(shù)據(jù):使用 read() 函數(shù)從文件中讀取二進(jìn)制數(shù)據(jù)。read() 函數(shù)的參數(shù)包括一個(gè)指向要讀取數(shù)據(jù)的指針和數(shù)據(jù)的長(zhǎng)度。
int data[5]; inputFile.read(reinterpret_cast<char*>(&data), sizeof(data));
- 關(guān)閉文件流:使用 close() 函數(shù)關(guān)閉文件流,確保數(shù)據(jù)寫(xiě)入或讀取完成。
outputFile.close(); inputFile.close();
注意:使用二進(jìn)制模式讀寫(xiě)文件需要對(duì)數(shù)據(jù)的存儲(chǔ)和大小有一個(gè)清晰的認(rèn)識(shí),確保正確地讀取和寫(xiě)入數(shù)據(jù)。同時(shí),在處理二進(jìn)制數(shù)據(jù)時(shí),需要注意避免出現(xiàn)類型轉(zhuǎn)換錯(cuò)誤,確保對(duì)二進(jìn)制數(shù)據(jù)的處理是正確的。
示例:
#include <iostream> #include <fstream> struct Data { int id; double value; }; int main() { // 寫(xiě)入二進(jìn)制數(shù)據(jù) std::ofstream outputFile("example.bin", std::ios::out | std::ios::binary); if(outputFile.is_open()) { Data data1 = {1, 3.14}; Data data2 = {2, 6.28}; // 將數(shù)據(jù)寫(xiě)入二進(jìn)制文件 outputFile.write(reinterpret_cast<char*>(&data1), sizeof(data1)); outputFile.write(reinterpret_cast<char*>(&data2), sizeof(data2)); outputFile.close(); } else { std::cerr << "Failed to open the file for writing." << std::endl; return 1; } // 讀取二進(jìn)制數(shù)據(jù) std::ifstream inputFile("example.bin", std::ios::in | std::ios::binary); if(inputFile.is_open()) { Data data1, data2; // 從文件中讀取二進(jìn)制數(shù)據(jù) inputFile.read(reinterpret_cast<char*>(&data1), sizeof(data1)); inputFile.read(reinterpret_cast<char*>(&data2), sizeof(data2)); // 輸出讀取的數(shù)據(jù) std::cout << "Data 1: " << data1.id << " " << data1.value << std::endl; std::cout << "Data 2: " << data2.id << " " << data2.value << std::endl; inputFile.close(); } else { std::cerr << "Failed to open the file for reading." << std::endl; return 1; } return 0; }
七、綜合示例
使用ofstream和ifstream來(lái)進(jìn)行文件讀寫(xiě),包括文本文件和二進(jìn)制文件的操作。
#include <iostream> #include <fstream> // 結(jié)構(gòu)體用于存儲(chǔ)二進(jìn)制文件數(shù)據(jù) struct Data { int id; double value; }; int main() { // 寫(xiě)入文本文件 std::ofstream textOutputFile("textfile.txt"); if(textOutputFile.is_open()) { textOutputFile << "This is a text file." << std::endl; textOutputFile << "It is used to demonstrate text file writing." << std::endl; textOutputFile.close(); } else { std::cerr << "Failed to open the text file for writing." << std::endl; return 1; } // 讀取文本文件 std::ifstream textInputFile("textfile.txt"); if(textInputFile.is_open()) { std::string line; while (std::getline(textInputFile, line)) { std::cout << line << std::endl; } textInputFile.close(); } else { std::cerr << "Failed to open the text file for reading." << std::endl; return 1; } // 寫(xiě)入二進(jìn)制文件 std::ofstream binaryOutputFile("binaryfile.bin", std::ios::out | std::ios::binary); if(binaryOutputFile.is_open()) { Data data1 = {1, 3.14}; Data data2 = {2, 6.28}; binaryOutputFile.write(reinterpret_cast<char*>(&data1), sizeof(data1)); binaryOutputFile.write(reinterpret_cast<char*>(&data2), sizeof(data2)); binaryOutputFile.close(); } else { std::cerr << "Failed to open the binary file for writing." << std::endl; return 1; } // 讀取二進(jìn)制文件 std::ifstream binaryInputFile("binaryfile.bin", std::ios::in | std::ios::binary); if(binaryInputFile.is_open()) { Data data1, data2; binaryInputFile.read(reinterpret_cast<char*>(&data1), sizeof(data1)); binaryInputFile.read(reinterpret_cast<char*>(&data2), sizeof(data2)); std::cout << "Data 1: " << data1.id << " " << data1.value << std::endl; std::cout << "Data 2: " << data2.id << " " << data2.value << std::endl; binaryInputFile.close(); } else { std::cerr << "Failed to open the binary file for reading." << std::endl; return 1; } return 0; }
八、總結(jié)
介紹了 C++ 文件流作為進(jìn)行文件讀寫(xiě)操作的工具,以及 ofstream 和 ifstream 類的基本作用和用法。
ofstream 的成員函數(shù):覆蓋了 ofstream 類的一些常用成員函數(shù),包括 open()、close()、is_open()、good()、bad()、operator<< 等。這些函數(shù)是實(shí)現(xiàn)文件寫(xiě)入操作時(shí)的關(guān)鍵。
使用流插入運(yùn)算符(<<)將數(shù)據(jù)寫(xiě)入文件。
文件的打開(kāi)模式,包括讀取、寫(xiě)入、追加和二進(jìn)制模式,以及如何在不同情況下選擇合適的打開(kāi)模式的方法。
處理文件打開(kāi)和讀寫(xiě)操作中可能發(fā)生的錯(cuò)誤,包括使用流的狀態(tài)來(lái)檢測(cè)錯(cuò)誤以及使用異常處理。
使用二進(jìn)制模式讀寫(xiě)文件:介紹了如何使用二進(jìn)制模式來(lái)進(jìn)行文件讀寫(xiě)操作,包括如何以二進(jìn)制模式打開(kāi)文件、寫(xiě)入數(shù)據(jù)到二進(jìn)制文件、從二進(jìn)制文件中讀取數(shù)據(jù)等。
以上就是C++通過(guò)ofstream和ifstream實(shí)現(xiàn)文件讀寫(xiě)的詳細(xì)內(nèi)容,更多關(guān)于C++ ofstream ifstream文件讀寫(xiě)的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
C++對(duì)象的淺復(fù)制和深復(fù)制詳解及簡(jiǎn)單實(shí)例
這篇文章主要介紹了C++對(duì)象的淺復(fù)制和深復(fù)制詳解及簡(jiǎn)單實(shí)例的相關(guān)資料,需要的朋友可以參考下2017-04-04

C語(yǔ)言中_string.h庫(kù)函數(shù)功能及其用法詳解

Qt無(wú)邊框窗口拖拽和陰影的實(shí)現(xiàn)方法