1. 程式人生 > 其它 >c++實現檔案的讀寫

c++實現檔案的讀寫

在c++ Primer第8章介紹了IO流,但是不是很詳細,結合網上查到的資料記錄如下

1 文字檔案的讀寫

1.1 寫文字檔案

定義好檔案輸出流後直接將string流入到輸出流即可,程式碼如下

/**
 * description: 向檔案中寫入文字
 * @param filePath  檔案路徑
 * @param content   寫入檔案的內容
 */
void writeText(const string &filePath, const string &content){
    ofstream ofs(filePath);  // 檔案存在開啟檔案,檔案不存在會自動建立檔案
    if (!ofs) cout << "檔案開啟失敗";
    ofs << content;
    ofs.close();  // 因為後面沒有其它操作,因此關閉檔案可省略,失去作用域後,檔案會自動關閉
}

int main() {
    const string str = "事了拂衣去\n"
                       "深藏功與名\n"
                       "十里殺一人\n"
                       "千里不留行";
    writeText("C:/Users/admin/Desktop/2.txt", str);
}

1.2 讀文字檔案

讀取文字檔案有兩種方式,一種是像讀取二進位制一樣,將檔案讀取到字元陣列緩衝區,然後輸出,另一種是讀入到字元流

第一種方式:讀入緩衝區

/**
 * description: 讀取文字檔案
 * @param filePath 檔案路徑
 * @return
 */
string readTextBuff(const string &filePath){
    ifstream ifs(filePath);
    char buff[100];  // 注意緩衝區大小不能太小,否則會溢位
    ifs.read(buff, size(buff));
    ifs.close();
    return {buff};  // 使用初始化列表返回string
}

int main() {
    cout << readTextBuff("C:/Users/admin/Desktop/2.txt");
}

第二種方式

string readTextSStream(const string &filePath) {
    ifstream ifs(filePath);
    ostringstream oss;      // 定義字元流
    oss << ifs.rdbuf();     // 將讀取到的文字流向字元流
    return oss.str();       // 獲取字元流中的文字
}

int main() {
    cout << readTextSStream("C:/Users/admin/Desktop/2.txt");
}

第二種方式不用去考慮緩衝區的問題,但兩種方式在返回值上都沒有考慮到返回值拷貝的問題,當讀取文字檔案較大時,需要返回很大的拷貝,因此,可以通過傳入一個引用來解決這個問題,修改程式碼如下

void readTextSStream(const string &filePath, string &str) {
    ifstream ifs(filePath);
    ostringstream oss;      // 定義字元流
    oss << ifs.rdbuf();     // 將讀取到的文字流向字元流
    str = oss.str();       // 獲取字元流中的文字
}

int main() {
    string string1;
    readTextSStream("C:/Users/admin/Desktop/2.txt", string1);
    cout << string1;
}

2 二進位制檔案的讀寫

二進位制檔案讀寫與文字檔案讀寫差不多,通過一個複製圖片檔案的例子來描述讀寫操作

/**
 * description: 複製檔案
 * @param readFilePath  被複制的檔案路徑
 * @param writeFilePath 複製後的檔案路徑
 */
void copyImage(const string &readFilePath, const string &writeFilePath){
    ifstream ifs(readFilePath);
    ofstream ofs(writeFilePath);
    char buff[1024];
    while (!ifs.eof()) {
        long count = ifs.read(buff, size(buff)).gcount();  // 讀取檔案時獲取讀取的位元組數,因為最後一次可能沒有1024個位元組
        ofs.write(buff, count);  // 將讀取的位元組寫入
    }
}

int main() {
    copyImage("C:/Users/admin/Desktop/goddess.jpg", "C:/Users/admin/Desktop/2.jpg");
}

剛學c++檔案讀寫,記錄一下,也希望新手能相互交流