C++ | 简单文件输入/输出

1 写入到文本文件

1.1 cout 和写入文本文件比较

写入文件的操作类似于 cout,两者的异同点如表1所示。

表1  控制台输出和文本文件写入
cout 控制台输出 文本文件输出
头文件 iostream fstream
所属类 iostream 定义ostream类 fstream 定义ofstream 类
名称空间 std, 引用元素cout和endl std, 引用元素ofstream
显示/输出 使用“cout和<<”显示 使用“ofstream和<<”输出
其他 需要声明若干个ofstream对象
需要用open()将ofstream对象与文件关联
结束用close()将其关闭

1.2 写入文本文件步骤

  • 包含头文件 fstream
  • 创建一个 ofstream 对象
  • 用 open() 将 ofstream 对象与文件关联
  • 使用 ofstream 对象(方法同 cout 的使用)
  • 利用 close() 关闭

利用open()关联对象和文本文件时,若果文件不存在则新建;如果文件存在,则先清空原始内容,然后写入新内容。

1.3 应用实例

#include <iostream>
// 1 包含头文件 
#include <fstream> 

int main() {
    using namespace std;
    char automobile[50];
    int year;
    // 2 创建ofstream对象
    ofstream outFile; 
    // 3 对象ofstream关联文件
    outFile.open("carinfo.txt");

    cout << "Enter the make and model of automobile: ";
    cin.getline(automobile, 50);
    cout << "Enter the model year: ";
    cin >> year;
    // 4 使用ofstream对象(同cout对象)
    outFile << fixed;
    outFile.precision(2);
    outFile.setf(ios_base::showpoint);
    outFile << "Make and model: " << automobile << endl;
    outFile << "Year: " << year << endl;
    // 5 关闭文件写入操作
    outFile.close(); 
    return 0;
}
// 输出到文件中的内容与应用cout对象显示在控制台的输出内容完全一样。

2 读取文本文件

2.1 cin 和读取文本文件比较

表2  控制台输入和文本文件读取
cin 控制台输入 文本文件读取
头文件 iostream fstream
所属类 iostream 定义istream类 fstream 定义ifstream 类
名称空间 std, 引用元素cin std, 引用元素ifstream
输入/读取 使用“cin和>>”读取 使用“ifstream和>>”读取
get() cin.get()读取一个字符,cin,getline()读取一行字符 ifstream和get()读取一个字符,ifstream和getline()读取一行字符
判断 cin和eof(), fail()判断输入是否成功 ifstream和eof(), fail()等判断输入是否成功
cin做条件 cin本身做测试条件,最后一个读取成功返回true ifstream本身做测试条件,最后一个读取成功返回true
其他 需要声明若干个ifstream对象
需要用open()将ifstream对象与文件关联
结束用close()将其关闭

2.2 读取文本文件步骤

  • 包含头文件 fstream
  • 创建一个 ifstream 对象
  • 用 open() 将 ifstream 对象与文件关联
  • 判断文件是否成功打开,这里需要检查是否超过 EOF,是否读取类型不匹配,是否最后一次读取文件出错。(这里由多种类方法可以选择使用)
  • 使用 ifstream 对象(方法同 cin 的使用)
  • 利用 close() 关闭读取操作

2.3 应用实例

#include <iostream>
// 1. 包含头文件
#include <fstream>
#include <cstdlib>
const int SIZE = 60;
int main() {
    using namespace std;
    char filename[SIZE];
    // 2. 创建ifstream对象
    ifstream inFile;

    cout << "Enter name of data file: ";
    cin.getline(filename, SIZE);
    // 3. 用open()关联ifstream对象
    inFile.open(filename);
    if (!inFile.is_open()) {
        cout << "Could not open the file " << filename << endl;
        cout << "Program terminating.\n";
        // cin.get();    // keep window open
        exit(EXIT_FAILURE);
    }
    double value;
    double sum = 0.0;
    int count = 0;

    inFile >> value;
    // 4. 判断文件是否正常打开
    while (inFile.good()) {
        ++count;            
        sum += value;      
        // 5. 使用ifstream对象
        inFile >> value; 
    }
    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 unknown reason.\n";

    if (count == 0)
        cout << "No data processed.\n";
    else {
        cout << "Items read: " << count << endl;
        cout << "Sum: " << sum << endl;
        cout << "Average: " << sum / count << endl;
    }
    // 6. 利用close()关闭
    inFile.close();
    return 0;
}

该实例中在步骤4 中应用了几个额外的检查方法,利用这些检查方法可以避免读取文本文件操作的可靠性:

(1)inFile.is_open()

检查文件是否成功打开,成功打开且没有任何错误时返回true。

(2)inFile.eof()

读取文件时不应超过EOF,当最后一次读取到EOF时,eof()返回true。

(3)inFile.fail()

最后一次读取中发生类型不匹配时,fail()返回true。

(4)inFile.good()

最后一次读取时发生文件损坏等情况时,good()方法返回true。这里应用时应考虑测试之前进行读取的规则(即在执行该语句之前,应当由数据读取操作,例如:inFile<<value)。

猜你喜欢

转载自blog.csdn.net/qq_38844835/article/details/121526341