W3School TIY Editor

  • W3School 在线教程
  • 改变方向
  • 暗黑模式
​x
 
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
​
int main () {
  // 创建文本文件
  ofstream MyWriteFile("filename.txt");
​
  // 写入文件
  MyWriteFile << "文件操作可能有些棘手,但也足够有趣!";
 
  // 关闭文件
  MyWriteFile.close();
​
  // 创建文本字符串用于输出文件内容
  string myText;
​
  // 读取文本文件
  ifstream MyReadFile("filename.txt");
​
  // 使用 while 循环和 getline() 函数逐行读取文件
  while (getline (MyReadFile, myText)) {
    // 输出文件内容
    cout << myText;
  }
​
  // 关闭文件
  MyReadFile.close();
}