亿迅智能制造网
工业4.0先进制造技术信息网站!
首页 | 制造技术 | 制造设备 | 工业物联网 | 工业材料 | 设备保养维修 | 工业编程 |
home  MfgRobots >> 亿迅智能制造网 >  >> Industrial programming >> C语言

C++文件I/O完全指南:fstream读写、打开模式、定位指针与完整实例

前文使用iostream的cin/cout处理标准输入输出。文件读写需fstream库,定义三类流类型:

序号类型与说明
1

ofstream

输出文件流:创建文件、写入数据。

2

ifstream

输入文件流:读取文件数据。

3

fstream

双向文件流:兼具ofstream/ifstream能力,可读可写可创建。

需包含<iostream>和<fstream>头文件。

打开文件

读写前必须打开。ofstream/fstream可写,ifstream仅读。标准语法:

void open(const char *filename, ios::openmode mode);

mode常用标志(可按位或|组合):

序号模式标志与说明
1

ios::app

追加模式:所有输出追加至文件末尾。

2

ios::ate

打开后定位至文件末尾(可读可写)。

3

ios::in

读模式。

4

ios::out

写模式。

5

ios::trunc

文件存在则截断(清空内容)。

组合示例:

ofstream outfile;
outfile.open("file.dat", ios::out | ios::trunc); // 写+截断
fstream afile;
afile.open("file.dat", ios::out | ios::in);    // 读写

关闭文件

程序结束自动刷新/关闭,但良好习惯显式关闭:void close();

写入文件

用流插入运算符<<,对象为ofstream/fstream而非cout。

读取文件

用流提取运算符>>,对象为ifstream/fstream而非cin。

完整读写示例

#include <fstream>
#include <iostream>
using namespace std;
int main() {
    char data[100];
    ofstream outfile;
    outfile.open("afile.dat");
    cout << "Writing to the file" << endl;
    cout << "Enter your name: ";
    cin.getline(data, 100);
    outfile << data << endl;
    cout << "Enter your age: ";
    cin >> data;
    cin.ignore(); // 清理换行残留
    outfile << data << endl;
    outfile.close();
    ifstream infile;
    infile.open("afile.dat");
    cout << "Reading from the file" << endl;
    infile >> data; cout << data << endl;
    infile >> data; cout << data << endl;
    infile.close();
    return 0;
}

样例交互:

$./a.out
Writing to the file
Enter your name: Zara
Enter your age: 9
Reading from the file
Zara
9

用getline()读整行,ignore()清理残留字符。

文件定位指针

istream/ostream提供重定位成员函数:

参数为长整型偏移量,第二参数指定基准:ios::beg(默认,文件头)、ios::cur(当前位置)、ios::end(文件尾)。示例:

fileObject.seekg(n);           // 定位到第n字节(从头)
fileObject.seekg(n, ios::cur); // 从当前位置前进n字节
fileObject.seekg(n, ios::end); // 从文件尾倒退n字节
fileObject.seekg(0, ios::end); // 定位到文件尾

C语言

  1. 平锉刀:木工金属加工必备修整工具全解析
  2. C++结构体与类:嵌入式开发者实战指南
  3. 掌握 C++ 变量、字面量与常量:核心概念与实战指南
  4. C++类与对象:面向对象编程实战指南
  5. C++ 动态内存管理:new 与 delete 专家级实战指南
  6. C++ 三种继承方式深度解析:public、protected 与 private
  7. C++ 友元函数与友元类:突破访问控制的利器
  8. C语言文件处理完全指南:fopen、fprintf、fread 与 fseek
  9. C 语言头文件详解:类型、用法与最佳实践
  10. C++日期时间完全指南:ctime库、tm结构体与格式化输出
  11. C++重载机制深度解析:函数重载与运算符重载全攻略
  12. 精通 Python 目录与文件操作