学懂C++ (十三):高级教程——C++ 文件和流详解

C++ 文件和流详解

在C++编程中,除了使用iostream标准库进行标准输入和输出(使用cincout)外,还可以使用fstream标准库来处理文件的输入和输出。fstream库定义了三个主要的数据类型:

  • ofstream:输出文件流,用于创建文件并向文件写入信息。
  • ifstream:输入文件流,用于从文件读取信息。
  • fstream:文件流,同时具有ofstreamifstream的功能,支持读写操作。

1、引入头文件

在使用文件流时,需要包含头文件<fstream><iostream>

#include <fstream>
#include <iostream>
using namespace std;

2、打开文件

在进行文件操作前,需要先打开文件。ofstreamfstream对象可以用于写操作,ifstream对象用于读操作。文件的打开模式可以通过open函数指定。

打开文件的标准语法
void open(const char *filename, ios::openmode mode);
常用的打开模式
  • ios::app:追加模式。所有写入都追加到文件末尾。
  • ios::ate:文件打开后定位到文件末尾。
  • ios::in:打开文件用于读取。
  • ios::out:打开文件用于写入。
  • ios::trunc:如果文件已经存在,则在打开文件之前清空其内容。

示例

ofstream outfile;
outfile.open("file.dat", ios::out | ios::trunc);

ifstream infile;
infile.open("file.dat", ios::in);

3、关闭文件

关闭文件是一个良好的编程习惯,确保所有资源被释放。使用close方法可以关闭文件。

outfile.close();
infile.close();

4、写入文件

使用流插入运算符(<<)可以向文件写入信息,与cout的使用方法类似。

ofstream outfile("file.dat");
outfile << "Hello, World!" << endl;
outfile.close();

5、读取文件

使用流提取运算符(>>)可以从文件读取信息,与cin的使用方法类似。

ifstream infile("file.dat");
string data;
infile >> data;
cout << data << endl;
infile.close();

6、读取和写入文件实例

以下示例展示了如何从文件读取和向文件写入信息。

#include <fstream>
#include <iostream>
using namespace std;

int main() {
    char data[100];

    // 以写模式打开文件
    ofstream outfile;
    outfile.open("afile.dat");

    cout << "Writing to the file" << endl;
    cout << "Enter your name: ";
    cin.getline(data, 100);
    outfile << data << endl;

    cout << "Enter your age: ";
    cin >> data;
    cin.ignore();
    outfile << data << endl;

    outfile.close();

    // 以读模式打开文件
    ifstream infile;
    infile.open("afile.dat");

    cout << "Reading from the file" << endl;
    infile >> data;
    cout << data << endl;

    infile >> data;
    cout << data << endl;

    infile.close();

    return 0;
}

7、文件指针的操作

可以使用以下方法操作文件指针:

  • seekg:设置输入位置
  • seekp:设置输出位置
  • tellg:获取输入位置
  • tellp:获取输出位置

istreamostream提供了用于重新定位文件位置指针的成员函数:seekg("seek get")和seekp("seek put")。

定位文件指针的示例1

ifstream fileObject("file.dat");

// 定位到文件的第n个字节(假设从文件开头开始)
fileObject.seekg(n, ios::beg);

// 从当前位置向后移n个字节
fileObject.seekg(n, ios::cur);

// 从文件末尾往回移n个字节
fileObject.seekg(n, ios::end);

// 定位到文件末尾
fileObject.seekg(0, ios::end);

定位文件指针的示例2

#include <iostream>
#include <fstream>

using namespace std;

int main() {
    ifstream inFile("input.txt", ios::binary);
    ofstream outFile("output.txt", ios::binary);

    if (inFile.is_open() && outFile.is_open()) {
        inFile.seekg(0, ios::end); // 定位到文件末尾
        streampos size = inFile.tellg(); // 获取文件大小
        inFile.seekg(0, ios::beg); // 定位到文件开头

        char* buffer = new char[size];
        inFile.read(buffer, size); // 读取整个文件到缓冲区
        outFile.write(buffer, size); // 写缓冲区到输出文件

        delete[] buffer;
        inFile.close();
        outFile.close();
    } else {
        cerr << "无法打开文件" << endl;
    }

    return 0;
}

8、错误处理

在进行文件操作时,可能会发生各种错误,如文件无法打开、读写失败等。可以使用以下方法检查文件流的状态:

  • good():无错误
  • eof():到达文件末尾
  • fail():非致命I/O错误
  • bad():致命I/O错误
    ifstream inFile("input.txt");
    
    if (inFile.is_open()) {
        // 检查文件流的状态
        if (inFile.good()) {
            // 继续处理文件
        } else if (inFile.eof()) {
            cerr << "到达文件末尾" << endl;
        } else if (inFile.fail()) {
            cerr << "非致命I/O错误" << endl;
        } else if (inFile.bad()) {
            cerr << "致命I/O错误" << endl;
        }
    
        inFile.close();
    } else {
        cerr << "无法打开文件" << endl;
    }
    

9、文件和流操作的综合示例

以下是一个综合示例,演示了文件的读取、写入、文件指针操作和错误处理。

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main() {
    // 打开输入文件
    ifstream inFile("input.txt");
    if (!inFile) {
        cerr << "无法打开输入文件" << endl;
        return 1;
    }

    // 打开输出文件
    ofstream outFile("output.txt");
    if (!outFile) {
        cerr << "无法打开输出文件" << endl;
        return 1;
    }

    string line;
    while (getline(inFile, line)) {
        // 逐行读取并写入输出文件
        outFile << line << endl;
    }

    // 检查读取是否成功
    if (inFile.eof()) {
        cout << "文件读取完成" << endl;
    } else if (inFile.fail()) {
        cerr << "文件读取失败" << endl;
    } else {
        cerr << "未知错误" << endl;
    }

    inFile.close();
    outFile.close();

    return 0;
}

 

总结

通过上述内容,我们了解了如何使用C++的fstream标准库进行文件的读取和写入操作,包括文件的打开、关闭、读写以及文件指针的操作。掌握这些基础知识对于处理文件输入输出操作非常重要。

  • 16
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值