c++读文件(一次全读/每行读/多次读)

2023-11-04

我以为这些都很容易在网上找到,谁知网上乱七八糟的东西太多,让我找了很久。。

开发环境为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()来转

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

c++读文件(一次全读/每行读/多次读) 的相关文章

随机推荐