在看这篇文章之前,先看看#include <fstream>的简介。
fstreamhttps://blog.youkuaiyun.com/NOIP1ding_c/article/details/144276289
这篇文章我来给大家几个fstream的应用。
应用
应用一
#include <fstream>
#include <iostream>
int main() {
std::fstream file;
file.open("example.txt", std::ios::out); // 以输出模式打开文件
if (!file) {
std::cerr << "Unable to open file!" << std::endl;
return 1; // 文件打开失败
}
file << "Hello, World!" << std::endl; // 写入文本
file.close(); // 关闭文件
return 0;
}
应用二
#include <fstream>
#include <iostream>
#include <string>
int main() {
std::fstream file;
file.open("example.txt", std::ios::in); // 以输入模式打开文件
if (!file) {
std::cerr << "Unable to open file!" << std::endl;
return 1; // 文件打开失败
}
std::string line;
while (getline(file, line)) { // 逐行读取
std::cout << line << std::endl;
}
file.close(); // 关闭文件
return 0;
}
应用三
#include <fstream>
#include <iostream>
int main() {
std::fstream file;
file.open("example.txt", std::ios::app); // 以追加模式打开文件
if (!file) {
std::cerr << "Unable to open file!" << std::endl;
return 1; // 文件打开失败
}
file << "Appending this line to the file." << std::endl; // 追加文本
file.close(); // 关闭文件
return 0;
}