在C 中將文件內容讀入字串
在C 中,有許多方法可以有效地將文件內容讀入單一字串字串變數。一種方法是使用 std::ifstream 類別。
以下程式碼片段提供如何使用 std::ifstream 和迭代器將檔案內容讀入字串的範例:
#include
#include
int main(int argc, char** argv)
{
std::ifstream ifs("myfile.txt");
std::string content( (std::istreambuf_iterator(ifs) ),
(std::istreambuf_iterator() ) );
return 0;
}
上面的程式碼開啟檔案「myfile.txt」進行讀取,並使用迭代器將檔案內容讀取到內容字串中。語句 std::ifstream ifs("myfile.txt");初始化ifs對象,並開啟指定檔案進行讀取。
第二行程式碼,std::string content( (std::istreambuf_iterator
將文件內容讀入內容字串後,您可以根據需要存取和操作該字串。例如,您可以將內容輸出到控制台或執行其他字串操作。
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3