1. 程式人生 > >c++讀檔案(一次全讀/每行讀/多次讀)

c++讀檔案(一次全讀/每行讀/多次讀)

我以為這些都很容易在網上找到,誰知網上亂七八糟的東西太多,讓我找了很久。。

開發環境為Windows,VS2013

一次全讀:

std::ifstream t(path); //讀檔案ifstream,寫檔案ofstream,可讀可寫fstream
std::stringstream buffer;
buffer << t.rdbuf();
std::string s = buffer.str();
std::cout << s;

每行讀/多次讀:

std::ifstream fin(path);
while (!fin) {
	fin.close(); //也有別的辦法可以讓指標指到檔案開頭
	fin.open(path, std::ios::in);
	Sleep(100); //太快了有時候不行,不知道為什麼
}
std::string line, res;
while (getline(fin, line)) {
	std::cout << line << '\n';
}
fin.close();
system("pause");

寫檔案:

std::ofstream outfile;
outfile.open(path, std::ios::trunc | std::ios::out);
outfile << json_string;
outfile.close();

std::ios::trunc保證寫之前清空檔案內容。path為string型別時用path.c_str()來轉