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

c++怎么读取文件里的内容和往文件里写入数据

在 C++ 中,读取和写入文件主要通过 <fstream> 头文件提供的类来实现。以下是详细的方法和示例:

1. 包含必要的头文件

#include <fstream>  // 文件流操作
#include <string>   // 使用字符串
#include <iostream> // 输入输出

2. 写入文件

使用 ofstream (输出文件流)

#include <fstream>
#include <iostream>int main() {// 创建输出文件流对象std::ofstream outFile;// 打开文件(如果文件不存在会自动创建)outFile.open("example.txt");// 检查文件是否成功打开if (!outFile.is_open()) {std::cout << "无法打开文件!" << std::endl;return 1;}// 写入数据outFile << "Hello, World!" << std::endl;outFile << "这是第二行" << std::endl;outFile << 123 << " " << 45.67 << std::endl;// 关闭文件outFile.close();std::cout << "数据写入成功!" << std::endl;return 0;
}

简化的写入方式

#include <fstream>int main() {// 使用构造函数直接打开文件std::ofstream outFile("example.txt");if (outFile) {  // 检查文件是否成功打开outFile << "简化方式写入数据" << std::endl;outFile << "自动会在析构时关闭文件" << std::endl;}return 0;
}

3. 读取文件

使用 ifstream (输入文件流)

#include <fstream>
#include <iostream>
#include <string>int main() {// 创建输入文件流对象std::ifstream inFile;inFile.open("example.txt");if (!inFile.is_open()) {std::cout << "无法打开文件!" << std::endl;return 1;}std::string line;// 逐行读取文件内容while (std::getline(inFile, line)) {std::cout << line << std::endl;}inFile.close();return 0;
}

其他读取方式

#include <fstream>
#include <iostream>
#include <string>int main() {std::ifstream inFile("example.txt");if (inFile) {// 方式1:逐词读取std::string word;while (inFile >> word) {std::cout << "单词: " << word << std::endl;}// 清空文件状态并重新定位到开头inFile.clear();inFile.seekg(0);// 方式2:读取单个字符char ch;while (inFile.get(ch)) {std::cout << ch;}}return 0;
}

4. 同时读写文件

使用 fstream

#include <fstream>
#include <iostream>int main() {// 打开文件用于读写std::fstream file("data.txt", std::ios::in | std::ios::out | std::ios::app);if (file.is_open()) {// 写入数据file << "新数据" << std::endl;// 移动到文件开头file.seekg(0);// 读取数据std::string content;while (std::getline(file, content)) {std::cout << content << std::endl;}file.close();}return 0;
}

5. 二进制文件操作

#include <fstream>
#include <iostream>struct Data {int id;double value;char name[20];
};int main() {// 写入二进制数据Data data = {1, 3.14, "Test"};std::ofstream outFile("binary.dat", std::ios::binary);if (outFile) {outFile.write(reinterpret_cast<char*>(&data), sizeof(Data));outFile.close();}// 读取二进制数据Data readData;std::ifstream inFile("binary.dat", std::ios::binary);if (inFile) {inFile.read(reinterpret_cast<char*>(&readData), sizeof(Data));std::cout << "ID: " << readData.id << ", Value: " << readData.value << ", Name: " << readData.name << std::endl;inFile.close();}return 0;
}

6. 文件打开模式

模式标志描述
std::ios::in打开用于读取
std::ios::out打开用于写入
std::ios::app追加模式(在文件末尾写入)
std::ios::ate打开后定位到文件末尾
std::ios::trunc如果文件存在,先截断
std::ios::binary二进制模式

重要提示

  1. 总是检查文件是否成功打开
  2. 记得关闭文件(虽然析构函数会自动关闭,但显式关闭是好习惯)
  3. 处理可能的异常(文件不存在、权限问题等)
  4. 使用合适的打开模式
  5. 二进制文件操作时要注意数据对齐和字节顺序

这些是 C++ 中文件操作的基本方法,根据具体需求选择合适的方式。


文章转载自:

http://XphFeD8g.kxnxf.cn
http://9N3Av7o4.kxnxf.cn
http://gZwFGybm.kxnxf.cn
http://bNVL2zoa.kxnxf.cn
http://PxX5Fa3K.kxnxf.cn
http://FEVEYT6r.kxnxf.cn
http://x1jk6sdA.kxnxf.cn
http://GvoVzJn6.kxnxf.cn
http://Db6MQ5DX.kxnxf.cn
http://93XSD10n.kxnxf.cn
http://EVhP8J4K.kxnxf.cn
http://qStcByAM.kxnxf.cn
http://q2Jjxu20.kxnxf.cn
http://kOjPBM2P.kxnxf.cn
http://c4yfQcs5.kxnxf.cn
http://CLC6Mizd.kxnxf.cn
http://NoTMhthI.kxnxf.cn
http://PZn8NDs3.kxnxf.cn
http://Mskk63rT.kxnxf.cn
http://2JMqjsgK.kxnxf.cn
http://ym5CcaJW.kxnxf.cn
http://kjdEEJne.kxnxf.cn
http://AJuGvrdc.kxnxf.cn
http://Osmor0Mo.kxnxf.cn
http://O0ReZEn3.kxnxf.cn
http://34SE0bvK.kxnxf.cn
http://PuBh5CVJ.kxnxf.cn
http://V2H0TfXx.kxnxf.cn
http://Uo8aViB1.kxnxf.cn
http://ld78T0Fu.kxnxf.cn
http://www.dtcms.com/a/380709.html

相关文章:

  • C++实战:搜索引擎项目(二)
  • 【Vue2 ✨】Vue2 入门之旅 · 进阶篇(七):Vue Router 原理解析
  • Java 多线程(三)
  • 【tips】el-input-number 数字输入框初始值超出限制值后,v-model的问题
  • Red Hat Linux 全版本镜像下载
  • vm.nr_hugepages参数配置错误导致系统无法启动
  • 【Qt】Qt 设置全局字体
  • c++ cpp 多叉树简单处理文件重复包含问题
  • YOLO系列目标检测模型演进与YOLOv13深度解析
  • 【基础知识】仿函数与匿名函数对比
  • 澳鹏数据集月度精选 | 覆盖全模态理解、复杂推理、海量真题的快速部署方案
  • 2025年- H136-Lc191.位1的个数(位运算)--Java版
  • 第五节 JavaScript——引用类型、DOM/BOM 与异步编程
  • 基础算法之二分算法 --- 2
  • Vue3+JS 复杂表单实战:从验证到性能优化的全流程方案
  • 基于RAG的智能客服系统
  • 建自己的Python项目仓库,使用工具:GitHub(远程仓库)、GitHub Desktop(版本控制工具)、VSCode(代码编辑器)
  • 容器使用卷
  • Vue3:根据el-input封装全局v-focus指令
  • 企业AI战略构建与成品选择指南
  • Semaphore和CountDownLatch
  • 实战ELK与AI MCP:构建高可用的智能化日志可观测体系
  • SAP-MM:SAP MM学习分享:深入浅出解析物料需求计划(MRP)及MRP配置图解
  • 【LLM】使用 Google ADK、Gemini、QDrant 和 MCP 构建深度研究系统
  • 【CSS学习笔记2】-css复合选择器
  • 186. Java 模式匹配 - Java 21 新特性:Record Pattern(记录模式匹配)
  • Electron下载失败
  • Origin绘制双Y轴网格叠加图|科研论文图表教程(附数据排列格式)
  • XXL-JOB框架SRC高频漏洞分析总结
  • 未启用Spring事务管理 执行mapper.xml文件的sql,为什么会自动提交