【C++】文件模式标志

常用文件模式标志

  1. std::ios::in

    • 以读模式打开文件。
    • 如果文件不存在,则打开失败。
    • 例如,用于读取文件内容。
  2. std::ios::out

    • 以写模式打开文件。
    • 如果文件不存在,则创建该文件。
    • 如果文件存在,则清空文件内容。
    • 例如,用于写入新内容到文件。
  3. std::ios::binary

    • 以二进制模式打开文件。
    • 读写时不进行任何格式化转换。
    • 例如,用于处理二进制文件。
  4. std::ios::ate

    • 文件打开后定位到文件末尾。
    • 可以用于追加数据,但要求与 std::ios::instd::ios::out 组合使用。
  5. std::ios::app

    • 以追加模式打开文件。
    • 每次写入操作都定位到文件末尾,不会覆盖文件内容。
    • 例如,用于追加日志记录到文件。
  6. std::ios::trunc

    • 如果文件存在,打开文件时清空文件内容。
    • 一般与 std::ios::out 组合使用。

文件模式标志的组合使用

这些标志可以通过按位或操作符 (|) 组合使用。例如:

  • std::ios::in | std::ios::out:以读写模式打开文件。
  • std::ios::out | std::ios::app:以写和追加模式打开文件。

示例代码

以下是一些使用不同文件模式标志的示例代码:

以读模式打开文件 (std::ios::in)
#include <fstream>
#include <iostream>

int main() {
    std::ifstream file("example.txt", std::ios::in);
    if (!file) {
        std::cerr << "File could not be opened for reading" << std::endl;
        return 1;
    }

    std::string line;
    while (std::getline(file, line)) {
        std::cout << line << std::endl;
    }

    file.close();
    return 0;
}
以写模式打开文件 (std::ios::out)
#include <fstream>
#include <iostream>

int main() {
    std::ofstream file("example.txt", std::ios::out);
    if (!file) {
        std::cerr << "File could not be opened for writing" << std::endl;
        return 1;
    }

    file << "Writing this text to the file." << std::endl;

    file.close();
    return 0;
}
以追加模式打开文件 (std::ios::app)
#include <fstream>
#include <iostream>

int main() {
    std::ofstream file("example.txt", std::ios::app);
    if (!file) {
        std::cerr << "File could not be opened for appending" << std::endl;
        return 1;
    }

    file << "Appending this text to the file." << std::endl;

    file.close();
    return 0;
}
以二进制模式读写文件 (std::ios::binary)
#include <fstream>
#include <iostream>

int main() {
    std::fstream file("example.bin", std::ios::in | std::ios::out | std::ios::binary);
    if (!file) {
        std::cerr << "File could not be opened in binary mode" << std::endl;
        return 1;
    }

    // Write binary data
    int number = 12345;
    file.write(reinterpret_cast<const char*>(&number), sizeof(number));

    // Read binary data
    file.seekg(0, std::ios::beg);
    int readNumber;
    file.read(reinterpret_cast<char*>(&readNumber), sizeof(readNumber));

    std::cout << "Read number: " << readNumber << std::endl;

    file.close();
    return 0;
}
  • 8
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值