打开文件

相关的函数为:fstream.open(path, mod)

其中mod表示文件的打开方式,可以使用或运算进行组合:

ios::in
ios::out
ios::ate 文件打开后定位到文件末尾。
ios::app 写入都追加到文件末尾。
ios::trunc 忽略已存在的文件内容
ios::binary 二进制方式打开

判断文件是否存在

  1. fstream file;
  2. file.open(path, mod, prot);
  3. if (!file) {
  4. cout << "文件不存在" << endl;
  5. }
  • 或者使用is_open()函数判断

创建文件

  1. fstream file;
  2. file.open(path, std::ios::out);
  3. fs.close();

从文件中读取行

  1. int main() {
  2. std::fstream fs;
  3. fs.open("../test.txt", std::ios::in);
  4. std::string str;
  5. while (std::getline(fs, str)) {
  6. std::cout << str << std::endl;
  7. }
  8. fs.close();
  9. }