【C++】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);

相关推荐

  1. 【C++】C++ 文件模式标志

    2024-07-18 09:34:03       24 阅读
  2. Dockerfile和.gitlab-ci.yml文件模板

    2024-07-18 09:34:03       53 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-18 09:34:03       66 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-18 09:34:03       70 阅读
  3. 在Django里面运行非项目文件

    2024-07-18 09:34:03       57 阅读
  4. Python语言-面向对象

    2024-07-18 09:34:03       68 阅读

热门阅读

  1. nginx域名跳转到另一个域名

    2024-07-18 09:34:03       23 阅读
  2. ios 设置行距和获取文本行数

    2024-07-18 09:34:03       21 阅读
  3. (86)组合环路--->(01)RGB值

    2024-07-18 09:34:03       18 阅读
  4. 详细说一下axios的特点

    2024-07-18 09:34:03       22 阅读
  5. log4j.appender.Logfile.File=./logs/its_log

    2024-07-18 09:34:03       20 阅读
  6. 七、python函数基础

    2024-07-18 09:34:03       20 阅读
  7. Junit单元测试常用断言

    2024-07-18 09:34:03       25 阅读
  8. app自动化测试缓存问题如何解决?

    2024-07-18 09:34:03       20 阅读
  9. 【Go系列】Go语言的测试

    2024-07-18 09:34:03       21 阅读