以下是C++中读取文件的基本语法:

#include <iostream>
#include <fstream>
using namespace std;

int main () {
   char data[100];

   // 以读模式打开文件
   ifstream infile;
   infile.open("afile.dat");

   cout << "Reading from the file" << endl;
   infile >> data;

   // 在屏幕上写入数据
   cout << data << endl;

   // 再次从文件读取数据,并显示它
   infile >> data;
   cout << data << endl;

   // 关闭打开的文件
   infile.close();

   return 0;
}

在上面的例子中,我们使用了ifstream类来打开和读取文件。该类提供了一种简单的方法来读取文本文件中的信息。我们也可以使用ofstream类来写入文件。

infile.open("afile.dat")语句打开一个名为afile.dat的文件。我们将该文件与程序放在同一个目录下,但也可以使用完整的路径来打开文件。例如,如果文件afile.dat位于C:\test\目录下,那么我们可以使用以下语句打开该文件:

infile.open("C:\\test\\afile.dat");

infile >> data语句从文件中读取数据,并将其存储在变量data中。我们可以使用该语句读取任何类型的数据,包括整数、浮点数、字符等。在上面的示例中,我们读取了一个字符串,并将其打印到屏幕上。

最后,我们使用infile.close()语句关闭文件。这是一个很好的习惯,因为它释放了与文件相关的资源。

文件读取C加加

原文地址: http://www.cveoy.top/t/topic/42A 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录