21xrx.com
2024-09-20 00:58:26 Friday
登录
文章检索 我的文章 写文章
C++文件流打开方式详解
2023-07-11 08:33:13 深夜i     --     --
C++ 文件流 打开方式 详解

C++ 文件流是一种用来与磁盘文件进行交互的数据流,使用文件流可以读取和写入文件。在 C++ 中,可以使用文件流库提供的操作来打开和关闭文件,同时还可以使用文件流对象来读取和写入文件。下面对 C++ 文件流的打开方式进行详解。

在 C++ 文件流中,有三种打开文件的方式:输入文件模式、输出文件模式和输入输出文件模式。输入文件模式用来读取文件,输出文件模式用来写入文件,而输入输出文件模式则可以同时进行读取和写入的操作。

输入文件模式使用 ifstream 类型的对象打开文件,输出文件模式使用 ofstream 类型的对象打开文件,而输入输出文件模式使用 fstream 类型的对象打开文件。下面分别介绍三种打开方式:

1、输入文件模式:使用 ifstream 类型的对象打开文件时,先调用 ifstream 构造函数来创建对象,然后使用成员函数 open() 来打开指定的文件。打开文件后,可以使用 >> 运算符或 getline() 成员函数来读取文件中的内容。

例如:


#include <fstream>

#include <iostream>

using namespace std;

int main()

{

  ifstream file;

  file.open("example.txt");

  if (!file)

  

    cout << "Can't open file!" << endl;

    return 0;

  

  int x;

  while (file >> x)

  

    cout << x << endl;

  

  file.close();

  return 0;

}

上述代码中,我们使用 ifstream 类型的对象来打开了 example.txt 文件,并使用 >> 运算符从该文件中读取整数,并打印在屏幕上。

2、输出文件模式:使用 ofstream 类型的对象打开文件时,先调用 ofstream 构造函数来创建对象,然后使用成员函数 open() 来打开指定的文件。打开文件后,可以使用 << 运算符来向文件中写入内容。

例如:


#include <fstream>

#include <iostream>

using namespace std;

int main()

{

  ofstream file;

  file.open("example.txt");

  if (!file)

  

    cout << "Can't open file!" << endl;

    return 0;

  

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

  

    file << i << endl;

  

  file.close();

  return 0;

}

上述代码中,我们使用 ofstream 类型的对象来打开了 example.txt 文件,并使用 << 运算符向该文件中写入整数。

3、输入输出文件模式:使用 fstream 类型的对象打开文件时,先调用 fstream 构造函数来创建对象,然后使用成员函数 open() 来打开指定的文件。打开文件后,可以使用 >> 运算符或 getline() 成员函数来读取文件中的内容,也可以使用 << 运算符向文件中写入内容。

例如:


#include <fstream>

#include <iostream>

using namespace std;

int main()

{

  fstream file;

  file.open("example.txt", ios::in | ios::out);

  if (!file)

  

    cout << "Can't open file!" << endl;

    return 0;

  

  int x;

  while (file >> x)

  {

    cout << x << endl;

    file << x * 2 << endl;

  }

  file.close();

  return 0;

}

上述代码中,我们使用 fstream 类型的对象来打开了 example.txt 文件,并同时进行读取和写入的操作。在 while 循环中,我们使用 >> 运算符从文件中读取整数,并打印在屏幕上,然后使用 << 运算符向文件中写入整数的两倍。

  
  

评论区

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