【C++温故知新】(九)文件的输入与输出

这是C++类重新复习学习笔记的第 九 篇,同专题的其他文章可以移步:https://www.jianshu.com/nb/39156122

文件的输入与输出也是基于(stream)的,和coutcin的操作类似。

文件的写入

基本条件

  • 必须包含头文件 fstream
  • 头文件 fstream 定义了一个用于处理输出的 ofstream
  • 需要声明一个或多个 ofstream 变量(对象),并命名
  • 必须指明名称空间 std
  • 需要将 ofstream 对象与文件关联起来。方法之一是使用 open() 方法
  • 使用完文件后,应使用方法 close() 将其关闭
  • 可结合使用 ofstream 对象和运算符 << 来输出各种类型的数据

一个文件写入的实例

#include<fstream>
using namespace std;
 
int main()
{
    string myString = "hello world!";

    ofstream ourFile;
    outFile.open("myFile.txt");
    outFile << myString;
    outFile.close();

    return 0;
}

文件的读取

基本条件

  • 必须包含头文件 fstream
  • 头文件 fstream 定义了一个用于处理输入的 ifstream
  • 需要声明一个或多个 ifstream 变量(对象),并命名
  • 需要将 ifstream 对象与文件关联起来。方法之一是使用 open() 方法
  • 读取完文件后,应使用方法 close() 将其关闭
  • 可结合使用 ifstream 对象和运算符 >> 来读取各种类型的数据
  • 可以使用 ifstream 对象和 get() 方法来读取一个字符,使用 ifstream 对象和 getline() 来读取一行字符
  • 可以结合使用 ifstreamcof()fai() 等方法来判断输入是否成功
  • ifstream 对象本身被用作测试条件时,如果最后一个读取操作成功,它将被转换为布尔值 true,否则被转换为 false

一个文件读取的实例

#include<fstream>
#include<iostream>
using namespace std;
 
int main()
{
    string fileName = "myFile.txt";

    ifstream inFile;
    inFile.open(fileName);
    if (!inFile.is_open())
    	cout << "Can't open the file: " << fileName;

    string readText;
    inFile >> readText;

    if (inFile.eof())
    	cout << "End of file reached.\n";
    else if (inFile.fail())
    	cout << "Input terminated by data mismatch.\n";
    else
    	cout << "Input terminated for other reasons.\n";

    inFile.close();

    return 0;
}

转载请注明出处,本文永久更新链接:https://blogs.littlegenius.xin/2019/08/28/【C-温故知新】九文件的输入与输出/

发布了44 篇原创文章 · 获赞 46 · 访问量 9154

猜你喜欢

转载自blog.csdn.net/qq_38962621/article/details/100128577