C++ 文件和流


C++ 文件和流

在C++中,文件是指存储在计算机本地磁盘上的一些数据集合。使用文件可以在程序执行时实现数据的永久性存储和读取。文件由一些字节序列组成,可以是一个简单的文本文件或者一个二进制文件。在C++中使用文件输入和输出流来进行读写操作,文件流类用于对文件进行处理。文件流的头文件是,这个文件中定义了三个类:ifstream、ofstream和fstream。

ofstream类为写入文件提供了支持,它的对象可以创建一个文件并向文件中写入数据。ofstream类的构造函数的参数是文件名,表示要写入的文件名。下面的示例演示了如何使用ofstream类写入数据:

#include <fstream>
#include <iostream>

using namespace std;

int main () {
   ofstream myfile;
   myfile.open ("example.txt");
   myfile << "Writing this to a file.\n";
   myfile.close();
   return 0;
}

在上面的程序中,将"example.txt"作为参数传递给open()函数,然后使用«操作符写入数据。最后使用close()函数关闭文件。

ifstream类是从文件中读取数据的类,它打开相应的文件,并返回一个输入流对象,这个对象可以从文件中读取数据。下面的示例演示了如何使用ifstream类读取数据:

#include <fstream>
#include <iostream>

using namespace std;

int main () {
   char buffer[256];
   ifstream myfile ("example.txt");
   if (myfile.is_open())
   {
      while (! myfile.eof() )
      {
         myfile.getline (buffer,256);
         cout << buffer << endl;
      }
      myfile.close();
   }
   else
   {
       cout << "Unable to open file"; 
   }
   return 0;
}

在上面的程序中,使用getline()函数逐行读取文本,并使用cout输出到屏幕。getchar()用来清除可能残余的缓冲区数据。

fstream类是从文件中读取和写入数据的类,它是文件输入和输出的组合,可以使用它来读取和写入文件。下面的示例演示了如何使用fstream类读取和写入数据:

#include <fstream>
#include <iostream>

using namespace std;

int main () {
   char data[100];

   ofstream outfile;
   outfile.open("example.dat");

   cout << "Writing to the file" << endl;
   cout << "Enter your name: "; 
   cin.getline(data, 100);

   outfile << data << endl;

   cout << "Enter your age: "; 
   cin >> data;
   cin.ignore();

   outfile << data << endl;

   outfile.close();

   ifstream infile; 
   infile.open("example.dat"); 

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

   cout << data << endl; 

   infile >> data; 
   cout << data << endl; 

   infile.close(); 

   return 0;
}

在上面的程序中,使用cin和cout进行数据的输入输出操作,然后使用ofstream将数据写入到文件"example.dat"中。使用ifstream从文件中读取数据,并将数据输出到屏幕上。

总结

文件和流是C++中非常重要的一个概念,可以帮助我们进行数据永久性的存储和读取。在C++中,有三个文件流类:ofstream、ifstream和fstream,分别用于写入文件、读取文件和读写文件。使用C++文件和流可以更加方便地操作数据,在实际的开发中,将用到大量的文件操作技巧。