C++ 對檔案的最常用操作
☆ 基本概念
- 根據檔案中資料的組織方式,可以將檔案分為 ASCII 檔案 和 二進制檔案,
- 前者又稱為文本檔案或字符檔案,后者又稱為內部格式檔案或位元組檔案,
- 本文講解針對 ASCII 檔案的基操,具體內容詳見代碼,
#include<fstream>
#include<string>
#include <iostream>
/*
ifstream 類,從 istream 類派生,用來支持從磁盤檔案輸入,
ofstream 類,從 ostream 類派生,用來支持向磁盤檔案輸出,
fstream 類,從 iostream 類派生,用來支持對磁盤檔案的輸入輸出,
*/
int main() {
// ofstream 是從記憶體到硬碟,ifstream 是從硬碟到記憶體,其實所謂的流緩沖就是記憶體空間
// 寫檔案
std::ofstream outfile1("file.txt", std::ios::out); //定義檔案流物件,打開磁盤檔案 file.txt
// 此方法與 open 函式作用相同,
// ios::out → 以輸出方式打開(沒有則創建,這是默認方式),如果有同名檔案夾,則將其原有內容全部清空
/* 常用引數
ios::app 以追加的方式打開檔案
ios::ate 檔案打開后定位到檔案尾,ios::app 就包含有此屬性
ios::binary 以二進制方式打開檔案,預設的方式是文本方式,
ios::in 檔案以輸入方式打開(檔案資料輸入到記憶體)
ios::out 檔案以輸出方式打開(記憶體資料輸出到檔案)
ios::nocreate 不建立檔案,所以檔案不存在時打開失敗
ios::noreplace 不覆寫檔案,所以打開檔案時如果檔案存在失敗
ios::trunc 如果檔案存在,把檔案長度設為 0
可以用 “ 或 ” 把以上屬性連接起來,如 ios::out | ios::binary*/
if (!outfile1) { // 打開失敗,outfile 回傳值為 0
std::cerr << "open failure" << '\n';
exit(1);
}
std::string content;
std::cout << "輸入你想輸入檔案的內容:\n";
// std::cin >> content; // 只能接收到空格以前
getline(std::cin, content); // 可以接收所有內容
/*文本檔案的讀寫
用插入器( << )向檔案輸出;
用析取器( >> )從檔案輸入*/
outfile1 << content; // 向磁盤檔案輸入內容
outfile1.close(); // 關閉磁盤檔案
// 讀檔案
std::string file{ "file.txt" };
std::ifstream outfile2(file);
if (!outfile1) { // 打開失敗,outfile 回傳值為 0
std::cerr << "open failure" << '\n';
exit(1);
}
/*
* 注釋方法由于回圈次數不定,會將最后一個字串重復輸出
std::string str;
std::string lastStr;
for (size_t i = 0; i < 100; ++i) {
outfile2 >> str;
lastStr += (str + " ");
}*/
std::string lastStr;
while (std::getline(outfile2, lastStr)); // 將檔案所有內容輸出到 lastStr
outfile2.close(); // 關閉磁盤檔案
std::cout << lastStr << std::endl;
system("pause");
return 0;
}
最后的效果
文本檔案
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/286978.html
標籤:其他
上一篇:iOS監聽H5頁面goBack回傳事件 & 網頁監聽APP回傳鍵 (NavigationBackItemInjection)


