版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/jxust_tj/article/details/78540878
我以为这些都很容易在网上找到,谁知网上乱七八糟的东西太多,让我找了很久。。
开发环境为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()来转