C++教程
C++控制语句
C++函数
C++数组
C++指针
C++对象
C++继承
C++多态
C++抽象
C++常用
C++ STL教程
C++迭代器
C++程序

C++文件和流

在 C++编程中,我们使用了 iostream 标准库,它提供 cin 和 cout 方法,分别用于从输入读取和写入到输出。
要读取并从文件中写入,我们正在使用称为 fstream 的标准C++库。让我们看看在fstream库中定义的数据类型是:
数据类型 说明
fstream 它用于创建文件,将信息写入文件以及从文件读取信息。
ifstream 它用于从文件中读取信息。
ofstream 它用于创建文件并将信息写入文件。

C++ FileStream示例: 写入文件

让我们看看使用C++ FileStream写入文本文件 testout.txt 的简单示例。编程。
#include <iostream>
#include <fstream>
using namespace std;
int main () {
  ofstream filestream("testout.txt");
  if (filestream.is_open())
  {
    filestream << "Welcome to lidihuo.\n";
    filestream << "C++ Tutorial.\n";
    filestream.close();
  }
  else cout <<"File opening is fail.";
  return 0;
}
输出:
The content of a text file testout.txt is set with the data:
Welcome to lidihuo.
C++ Tutorial.

C++ FileStream示例: 从文件读取

让我们看看使用C++ FileStream从文本文件 testout.txt 读取的简单示例。编程。
#include <iostream>
#include <fstream>
using namespace std;
int main () {
  string srg;
  ifstream filestream("testout.txt");
  if (filestream.is_open())
  {
    while ( getline (filestream,srg) )
    {
      cout << srg <<endl;
    }
    filestream.close();
  }
  else {
      cout << "File opening is fail."<<endl; 
    }
  return 0;
}
注意: 在运行代码之前,需要创建一个名为" testout.txt"的文本文件,并且在下面给出文本文件的内容: 欢迎使用lidihuo。 C++教程。
输出:
Welcome to lidihuo.
C++ Tutorial.

C++读写示例

让我们看一下将数据写入文本文件 testout.txt 的简单示例,然后阅读使用C++ FileStream编程从文件读取数据。
#include <fstream>
#include <iostream>
using namespace std;
int main () {
   char input[75];
   ofstream os;
   os.open("testout.txt");
   cout <<"Writing to a text file:" << endl;
   cout << "Please Enter your name: "; 
   cin.getline(input, 100);
   os << input << endl;
   cout << "Please Enter your age: "; 
   cin >> input;
   cin.ignore();
   os << input << endl;
   os.close();
   ifstream is; 
   string line;
   is.open("testout.txt"); 
   cout << "Reading from a text file:" << endl; 
   while (getline (is,line))
   {
   cout << line << endl;
   }  
   is.close();
   return 0;
}
输出:
Writing to a text file:  
 Please Enter your name: Nakul Jain    
Please Enter your age: 22  
 Reading from a text file:   Nakul Jain  
 22

昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4