21xrx.com
2024-09-19 09:56:31 Thursday
登录
文章检索 我的文章 写文章
C++中的文件读写技巧
2023-07-12 19:02:13 深夜i     --     --
C++ 文件读 文件写 技巧 文件流

C++是一种面向对象的编程语言,它在处理文件读写方面有着强大的能力和灵活性。本文将介绍一些在C++中进行文件读写的基本技巧。

1. 文件的打开和关闭

在进行文件读写操作之前,首先需要打开文件。C++中可以使用fstream库的open()函数打开文件,open()函数有两个参数:文件名和文件打开模式。打开模式可以是in、out或app,分别表示打开文件进行读取、写入或在文件末尾追加。

打开文件后,要及时关闭文件,可以使用close()函数来关闭文件。如果程序崩溃或终止,也会自动关闭文件。

例如,下面的代码演示了如何打开和关闭文件:


#include <fstream>

using namespace std;

int main()

{

  // 打开文件

  ofstream fout("example.txt");

  if (fout.is_open())

  {

    // 向文件写入数据

    fout << "This is an example file." << endl;

    // 关闭文件

    fout.close();

  }

  return 0;

}

2. 文件的读取和写入

在打开文件后,可以使用流运算符<<和>>来进行文件的读写操作。符号<<表示从变量写入文件,符号>>表示从文件读取到变量中。

例如,下面的代码演示了如何从文件中读取数据:


#include <fstream>

#include <iostream>

using namespace std;

int main()

{

  ifstream fin("example.txt");

  if (fin.is_open())

  {

    string line;

    while (getline(fin, line))

    

      cout << line << endl;

    

    fin.close();

  }

  return 0;

}

3. 文件的追加

在需要将新数据附加到文件的结尾时,可以使用out或app打开模式。如果使用out模式打开文件,会覆盖文件中的原有数据;如果使用app模式打开文件,则会在文件的末尾追加数据。

例如,下面的代码演示了如何向文件中追加数据:


#include <fstream>

using namespace std;

int main()

{

  // 将新数据附加到文件末尾

  ofstream fout("example.txt", ios::app);

  if (fout.is_open())

  {

    fout << "This is a new line." << endl;

    fout.close();

  }

  return 0;

}

4. 二进制文件的读写

在进行二进制文件的读写时,需要使用二进制文件打开模式。在二进制文件中,每个数据类型都采用确定的字节数,因此在读写时要注意数据类型和字节数的匹配。

例如,下面的代码演示了如何读写二进制文件:


#include <fstream>

#include <iostream>

using namespace std;

struct Student

{

  char name[20];

  int age;

};

int main()

{

  // 写入二进制文件

  Student stu[2] = { 18, 17};

  ofstream fout("example.dat", ios::binary);

  if (fout.is_open())

  {

    fout.write((char*)&stu, sizeof(stu));

    fout.close();

  }

  // 读取二进制文件

  Student st[2];

  ifstream fin("example.dat", ios::binary);

  if (fin.is_open())

  {

    fin.read((char*)&st, sizeof(st));

    for (int i = 0; i < 2; i++)

    {

      cout << "Name: " << st[i].name << endl;

      cout << "Age: " << st[i].age << endl;

    }

    fin.close();

  }

  return 0;

}

以上是C++中文件读写的一些基本技巧,掌握这些技巧能够使文件读写操作更加灵活和高效。在实际开发中,需要根据实际情况选择合适的方法进行操作。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复