21xrx.com
2024-05-20 08:36:16 Monday
登录
文章检索 我的文章 写文章
C++文件流输入输出指南
2023-07-03 02:21:05 深夜i     --     --
C++ 文件流 输入 输出 指南

C++是一种流行的面向对象编程语言,在处理文件输入输出方面非常强大和灵活。C++文件流可以用于读取文件中的数据,并将数据写入文件。本文将介绍如何使用C++文件流进行文件输入输出。

文件流的概念

C++文件流是从iostreams库派生而来的。文件流用于访问文件和执行文件输入输出操作。文件流可以分为输入和输出两种类型。在C++中,文件流可以通过三种方式访问文件:

1. ifstream类是用于读文件的文件流,也被称为输入文件流。

2. ofstream类是用于写文件的文件流,也被称为输出文件流。

3. fstream类可以在文件中进行读写操作,也称为输入输出文件流。

文件读取与写入

文件读取可以使用ifstream类,具体的操作如下:


#include <fstream>

#include <iostream>

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类创建了一个输入文件流对象,使用is_open()函数验证是否打开示例文件,然后逐行读取文件内容进行操作,在文件读取结束时关闭文件。

文件写入可以使用ofstream类,具体的操作如下:


#include <fstream>

#include <iostream>

using namespace std;

int main ()

{

  ofstream myfile;

  myfile.open ("example.txt"); //打开文件

  myfile << "This is a line." << endl; //在文件中写入一行

  myfile.close(); //关闭文件

  return 0;

}

上述代码使用了ofstream类创建了一个输出文件流对象,使用open()函数打开示例文件,然后在文件中写入一行数据并关闭文件。

读写操作

fstream类处理的是文件的读写操作,具体的操作如下:


#include <fstream>

#include <iostream>

using namespace std;

int main()

{

  string line;

  fstream myfile("example.txt", ios::in | ios::out | ios::app); //打开文件(指定为读写模式)

  if (myfile.is_open()) //确认文件是否打开

  {

    while (getline(myfile, line)) //循环读取文件行

    {

      cout << line << '\n'; //打印文件内容

    }

    myfile << "This is a new line." << endl; //在文件中写入一行新数据

    myfile.close(); //关闭文件

  }

  else cout << "Unable to open file"; //若文件打开失败则提供提示

  return 0;

}

上述代码使用了fstream类创建一个输入输出文件流对象,使用is_open()函数验证示例文件是否被正常打开,然后逐行读取文件内容进行操作,并在文件中加入新的数据。最后关闭文件。

本文提供了C++文件流输入输出指南,涵盖了使用C++文件流进行文件读取和文件写入的相关内容。使用这些方法和技巧,您可以更加方便地使用C++进行文件操作。

  
  

评论区

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