21xrx.com
2025-03-29 10:42:11 Saturday
文章检索 我的文章 写文章
C++文件读写的示例代码
2023-07-05 12:04:22 深夜i     12     0
C++ 文件读写 示例代码

C++文件读写是C++语言中常见的一种操作。通过文件读写,我们可以将数据从文件中读取到程序中,或者将程序中的数据写入到文件中。本文将提供一些示例代码来展示如何在C++中进行文件读写操作。

1. 写文件示例

以下示例代码演示了如何在C++中写入一个文件。

#include <iostream>
#include <fstream>
using namespace std;
int main() {
  ofstream outfile;
  outfile.open("example.txt");
  outfile << "Hello, World!";
  outfile.close();
  return 0;
}

这段代码使用了`std::ofstream`类来打开一个文件,并将一条字符串写入到该文件中。最后,文件使用`.close()`方法关闭。

2. 读文件示例

以下示例代码演示了如何在C++中读取一个文件。

#include <iostream>
#include <fstream>
using namespace std;
int main() {
  ifstream infile;
  infile.open("example.txt");
  string data;
  infile >> data;
  cout << data << endl;
  infile.close();
  return 0;
}

这段代码使用了`std::ifstream`类来打开一个文件,并从该文件中读取一个字符串。最后,文件使用`close()`方法关闭。

3. 添加文件示例

以下示例代码演示了如何在C++中向一个文件中添加内容。

#include <iostream>
#include <fstream>
using namespace std;
int main() {
  ofstream outfile;
  outfile.open("example.txt", ios::app);
  outfile << "\nBye, World!";
  outfile.close();
  return 0;
}

这段代码使用了`std::ofstream`类来打开一个文件,并向该文件中追加一条新的内容。`ios::app`表示文件将以附加模式打开,而非覆盖模式。

总的来说,文件读写是C++中常见的操作之一,通过使用`std::ofstream`、`std::ifstream`或`std::fstream`类,你可以很轻松地在程序中进行文件读写操作。同时也需要注意文件的打开方式和关闭方式,以免出现意外情况。

  
  

评论区

请求出错了