13 C++ 文件操作用法详解

 V信公众号:  程序员架构笔记

在C++中,文件的打开、关闭、读写操作以及二进制文件与文本文件的处理是常见的文件操作任务。以下是这些操作的详细说明和示例代码。

1. 文件的打开与关闭

在C++中,文件操作通常使用fstreamifstreamofstream类。这些类分别用于文件的输入输出、仅输入和仅输出操作。

打开文件
  • 使用open()函数打开文件。

  • 可以指定文件的打开模式,如ios::in(读)、ios::out(写)、ios::app(追加)、ios::binary(二进制模式)等。

关闭文件
  • 使用close()函数关闭文件。

#include <fstream>
#include <iostream>

int main() {
    std::ofstream outFile;
    outFile.open("example.txt", std::ios::out); // 打开文件用于写入

    if (outFile.is_open()) {
        outFile << "Hello, World!" << std::endl; // 写入数据
        outFile.close(); // 关闭文件
    } else {
        std::cerr << "Failed to open file!" << std::endl;
    }

    return 0;
}

2. 文件的读写操作

写入文件
  • 使用<<操作符将数据写入文件。

读取文件
  • 使用>>操作符或getline()函数从文件中读取数据。

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

int main() {
    // 写入文件
    std::ofstream outFile("example.txt");
    if (outFile.is_open()) {
        outFile << "Hello, World!" << std::endl;
        outFile << "This is a test file." << std::endl;
        outFile.close();
    } else {
        std::cerr << "Failed to open file for writing!" << std::endl;
    }

    // 读取文件
    std::ifstream inFile("example.txt");
    std::string line;
    if (inFile.is_open()) {
        while (std::getline(inFile, line)) {
            std::cout << line << std::endl;
        }
        inFile.close();
    } else {
        std::cerr << "Failed to open file for reading!" << std::endl;
    }

    return 0;
}

3. 二进制文件与文本文件的处理

文本文件
  • 文本文件以可读的字符形式存储数据。

  • 使用<<>>操作符进行读写。

二进制文件
  • 二进制文件以二进制形式存储数据,通常用于存储非文本数据(如图像、音频等)。

  • 使用read()write()函数进行读写。

#include <fstream>
#include <iostream>

struct Data {
    int id;
    char name[20];
};

int main() {
    // 写入二进制文件
    Data data = {1, "Alice"};
    std::ofstream outFile("data.bin", std::ios::binary);
    if (outFile.is_open()) {
        outFile.write(reinterpret_cast<char*>(&data), sizeof(data));
        outFile.close();
    } else {
        std::cerr << "Failed to open binary file for writing!" << std::endl;
    }

    // 读取二进制文件
    Data readData;
    std::ifstream inFile("data.bin", std::ios::binary);
    if (inFile.is_open()) {
        inFile.read(reinterpret_cast<char*>(&readData), sizeof(readData));
        inFile.close();
        std::cout << "ID: " << readData.id << ", Name: " << readData.name << std::endl;
    } else {
        std::cerr << "Failed to open binary file for reading!" << std::endl;
    }

    return 0;
}

总结

  • 文件的打开与关闭:使用open()close()函数。

  • 文件的读写操作:使用<<>>getline()read()write()函数。

  • 二进制文件与文本文件的处理:文本文件使用字符流操作,二进制文件使用二进制流操作。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员架构笔记

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值