21xrx.com
2025-07-08 21:47:42 Tuesday
登录
文章检索 我的文章 写文章
C++中的文件读写操作——写入和读取数据
2023-07-05 06:29:36 深夜i     19     0
C++ 文件读写 写入数据 读取数据

C++是一种常见的编程语言,广泛应用于计算机程序开发中。在C++语言中,文件读写操作是常见的操作之一,可以用于存储和读取数据。文件操作可以帮助我们将数据保存下来,也可以从文件中读取数据,这对于处理大量数据的程序开发来说非常有用。

在C++中,写入文件需要使用ofstream类,该类提供了一些方法,使我们可以将数据写入文件中。要进行文件写入,我们首先需要打开一个文件。示例代码如下:

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
  ofstream myfile ("example.txt");
  if (myfile.is_open())
  {
    myfile << "This is a line.\n";
    myfile << "This is another line.\n";
    myfile.close();
  }
  else cout << "Unable to open file.";
  return 0;
}

上面的代码使用了ofstream类来打开一个example.txt文件,然后向文件中写入两行文本。代码运行后会输出一个example.txt文件。我们可以使用如下的C++代码来读取该文件中的数据:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
  string line;
  ifstream myfile ("example.txt");
  if (myfile.is_open())
  {
    while ( getline (myfile,line) )
    {
      cout << line << '\n';
    }
    myfile.close();
  }
  else cout << "Unable to open file";
  return 0;
}

上面的代码使用了ifstream类打开了example.txt文件,并循环读取其中每一行文本。每一行文本都被输出到了控制台上。

在文件读写过程中,还有一些其他重要的方法。例如,在进行文件写入时,如果想以二进制的方式写入文件,可以使用ofstream类的write()方法:

ofstream outfile("example2.dat", ios::out | ios::binary);
int x = 10;
char ch = 'a';
outfile.write((char*)&x, sizeof(x));
outfile.write(&ch, sizeof(ch));
outfile.close();

上面的代码将一个整数和一个字符数据以二进制的方式写入了文件example2.dat中。在读取这些数据时,可以使用ifstream类的read()方法来读取它们:

int x;
char ch;
infile.read((char*)&x, sizeof(x));
infile.read(&ch, sizeof(ch));

总之,C++中的文件读写操作是计算机编程中不可或缺的部分。通过使用ifstream类和ofstream类,我们可以轻松地读写文本和二进制文件,并将文件保存在计算机上。熟练掌握文件读写操作,将有助于我们开发出更复杂、更强大的程序。

  
  

评论区