Re: [問題] C++ 將檔案讀入 std::string
※ 引述《out99 ( )》之銘言:
: 開發平台(Platform): (Ex: VC++, GCC, Linux, ...)
: VC++
: 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...)
: 問題(Question):
: 我想要一次將整個檔案讀進 std::string
: 而不是用 while 一行一行讀取再 append string
: 我直接使用 std::getline() 第三個參數 delim 丟入 '\0' 處理
: 測試過幾個檔案「看起來」沒有問題
: 我想問的是會不會有特殊情形導致這個方式讀出來的內容是錯誤的?
你底下假設要讀的是 ASCII 檔, 用 '\0' 當 delimiter 應該不會有問題.
: 直接假設「檔案的第一個 '\0' 字元就是整個檔案的結尾」是正確的嗎?
這個假設並非對所有檔案都成立.
例如執行檔裡面要存字串常數就會以 '\0' 結尾, 而非檔尾.
ASCII 檔用 '\0' 當 delimiter 之所以會讀進整個檔不是因為「讀到第一個 '\0'
字元」, 而是「直到檔尾都還沒讀到 '\0' 所以回傳目前讀到的部份」.
要對所有檔案都通用可以參考
http://stackoverflow.com/questions/2602013
第二個答案:
std::stringstream buffer;
buffer << fin.rdbuf();
str = buffer.str();
: 謝謝
: 餵入的資料(Input):
: 內容為 ASCII 字元,不包含其它特殊字元的文字檔。
: 預期的正確結果(Expected Output):
: 錯誤結果(Wrong Output):
: 程式碼(Code):(請善用置底文網頁, 記得排版)
: #include <iostream>
: #include <string>
: #include <fstream>
: using namespace std;
: int main(int argc, char** argv)
: {
: string str;
: ifstream fin(argv[1], ios::in);
: if (fin.fail())
: return 1;
: getline(fin, str, '\0');
: fin.close();
: cout << str;
: return 0;
: }
: 補充說明(Supplement):
--
And in that line now was a whiskered old man,
with a linen cap and a crooked nose,
who waited in a place called the Stardust Band Shell
to share his part of the secret of heaven:
that each affects the other and the other affects the next,
and the world is full of stories, but the stories are all one.
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 128.36.232.22
※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1432001664.A.B62.html
推
05/19 14:37, , 1F
05/19 14:37, 1F
推
05/21 11:31, , 2F
05/21 11:31, 2F
→
05/21 11:33, , 3F
05/21 11:33, 3F
→
05/21 12:10, , 4F
05/21 12:10, 4F
→
05/21 12:11, , 5F
05/21 12:11, 5F
→
05/21 12:12, , 6F
05/21 12:12, 6F
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 2 之 3 篇):