当前位置: 首页 > news >正文

c++学习系列----002.写文件

c++ 写文件

文章目录

  • c++ 写文件
    • 1️⃣ 使用 `ofstream` 写入文本文件
    • 2️⃣ 追加模式写入
    • 3️⃣ 写入二进制文件
    • 4️⃣ 使用 `fstream` 进行读写
    • 5️⃣ 使用 `fprintf()`(C 方式)
    • 6️⃣ 使用 `write()` 低级 I/O 方式
    • 推荐方式

C++ 写文件的几种方式主要有以下几种:

方式适用场景示例
std::ofstream文本写入file << "text"
std::ofstream (std::ios::app)追加文本file << "text"
std::ofstream (std::ios::binary)二进制写入file.write(data, size)
std::fstream读写模式file << "text"
fprintf() (C方式)C风格写入fprintf(file, "text")
write() (低级I/O)高效文件操作write(fd, data, size)

1️⃣ 使用 ofstream 写入文本文件

最常见的方法,适用于写入纯文本数据。

#include <iostream>
#include <fstream>

int main() {
    std::ofstream file("output.txt");  // 打开文件进行写入(默认会覆盖原文件)
    if (!file) {
        std::cerr << "无法打开文件!" << std::endl;
        return 1;
    }

    file << "Hello, World!" << std::endl;  // 写入文本
    file.close();  // 关闭文件

    return 0;
}

🔹 说明

  • std::ofstream file("output.txt"); 打开文件,默认覆盖原文件内容。
  • file << "Hello, World!" << std::endl;流式 方式写入数据。

2️⃣ 追加模式写入

在文件末尾追加内容,不覆盖原有内容,使用 std::ios::app

#include <fstream>

int main() {
    std::ofstream file("output.txt", std::ios::app);  // 追加模式
    if (file) {
        file << "追加内容..." << std::endl;
    }
    file.close();
    return 0;
}

🔹 说明

  • std::ios::app 追加模式,不会清空原文件,写入内容会添加到末尾。

3️⃣ 写入二进制文件

使用 std::ios::binary 以二进制模式写入文件(适用于写入结构体、图片、音频等)。

#include <fstream>

int main() {
    std::ofstream file("data.bin", std::ios::binary);  // 以二进制模式打开
    if (!file) {
        std::cerr << "无法打开文件!" << std::endl;
        return 1;
    }

    int number = 12345;
    file.write(reinterpret_cast<char*>(&number), sizeof(number));  // 写入二进制数据
    file.close();

    return 0;
}

🔹 说明

  • std::ios::binary二进制 方式打开文件,适用于非文本数据。
  • file.write(reinterpret_cast<char*>(&number), sizeof(number)); 直接写入数据的 二进制表示

4️⃣ 使用 fstream 进行读写

std::fstream 既可以读也可以写,适用于需要修改文件的情况。

#include <fstream>

int main() {
    std::fstream file("output.txt", std::ios::in | std::ios::out | std::ios::app);
    if (!file) {
        std::cerr << "无法打开文件!" << std::endl;
        return 1;
    }

    file << "这是一个可以读写的文件!" << std::endl;
    file.close();

    return 0;
}

🔹 说明

  • std::ios::in | std::ios::out | std::ios::app可读可写,并且追加模式

5️⃣ 使用 fprintf()(C 方式)

C 语言的 FILE*,可以使用 fprintf()

#include <cstdio>

int main() {
    FILE* file = fopen("output.txt", "w");  // "w" 代表写模式,覆盖原文件
    if (!file) {
        perror("无法打开文件");
        return 1;
    }

    fprintf(file, "Hello, World!\n");  // 格式化写入
    fclose(file);  // 关闭文件

    return 0;
}

🔹 说明

  • fopen("output.txt", "w") 以写模式打开文件(覆盖原内容)。
  • fprintf(file, "Hello, World!\n") 格式化写入,类似 printf()
  • fclose(file); 关闭文件,避免资源泄漏。

追加写入,可以改为:

FILE* file = fopen("output.txt", "a");  // "a" 追加模式

6️⃣ 使用 write() 低级 I/O 方式

write() 是 POSIX 系统(如 Linux)中的低级 I/O 操作,可以提高效率。

#include <fcntl.h>
#include <unistd.h>

int main() {
    int fd = open("output.txt", O_WRONLY | O_CREAT | O_TRUNC, 0644);
    if (fd == -1) {
        perror("无法打开文件");
        return 1;
    }

    const char* text = "Hello, World!\n";
    write(fd, text, 14);  // 低级写入
    close(fd);  // 关闭文件

    return 0;
}

🔹 说明

  • open("output.txt", O_WRONLY | O_CREAT | O_TRUNC, 0644)写模式 打开或创建文件。
  • write(fd, text, 14); 直接写入 字节流
  • close(fd); 关闭文件。

推荐方式

  • 一般文本写入std::ofstream
  • 追加模式std::ofstream + std::ios::app
  • 二进制文件std::ofstream + std::ios::binary
  • 需要读写std::fstream
  • 低级 I/Owrite()(适用于大文件或性能关键场景)

相关文章:

  • Java面试八股—Redis篇
  • 空洞卷积(膨胀卷积)(Dilated Convolution / Atrous Convolution)
  • 【Redis事务】redis中事务的使用
  • kafka rocketmq rabbitmq 都是怎么实现顺序消费的
  • UG的一些操作步骤(自用笔记1)
  • 初阶数据结构习题【12】(3顺序表和链表)——138.随机表的复制
  • 【论文阅读】Looking to Listen at the Cocktail Party:一种与说话人无关的语音分离视听模型
  • IP风险度自检,互联网的安全“指南针”
  • 「Unity3D」UGUI运行时设置元素的锚点Anchor,维持元素Rect的显示不变,即待在原处
  • go的gmp
  • 在rv1106上部署vue3
  • Python 中 lambda 表达式、推导式和其他函数用法对比
  • DML介绍
  • 智慧应急消防解决方案(35页PPT)(文末有下载方式)
  • Spring Cloud Stream - 构建高可靠消息驱动与事件溯源架构
  • 【动态规划篇】746.使用最小花费爬楼梯
  • SAP 标准弹窗 自定义弹窗 (所有弹窗弹框大全)
  • 鸿蒙系统liteos_m开发环境配置
  • 让网站变得更智能!架构标记如何提升SEO并吸引更多流量?
  • Word填写窗口功能详解:如何让文档填写更高效?
  • 怎么做网站的图片跳转/seo优化是怎么回事呢
  • 广州网站建设招标/上海站群优化公司
  • 泰州做网站的/百度搜索关键词推广
  • 国内适合个人做外贸的网站有哪些/360seo关键词优化
  • dede被挂赌博网站木马/百度推广开户渠道
  • 网站建设课程大纲/seo网站优化专员