前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++中文件读写操作

C++中文件读写操作

作者头像
李小白是一只喵
发布2020-04-23 15:23:04
9280
发布2020-04-23 15:23:04
举报
文章被收录于专栏:算法微时光算法微时光

fstreaml类

fstream提供了三个类,用来实现c++对文件的操作(文件的创建、读、写)

  1. fstream 文件流
  2. ifstream 输入文件流
  3. ofstream 输出文件流
打开文件

文件打开模式:

标示

含义

ios::in

只读

ios::out

只写

ios::app

从文件末尾开始写,防止丢失文件中原来就有的内容

ios::binary

二进制模式

ios::nocreate

打开一个文件时,如果文件不存在,不创建文件

ios::noreplace

打开一个文件时,如果文件不存在,创建该文件

ios::trunc

打开一个文件,然后清空内容

ios::ate

打开一个文件时,将位置移动到文件尾

使用代码举例:

代码语言:javascript
复制
  ifstream infile;   //输入流
  ofstream outfile("test.txt", ios::out);   //输出流
  infile.open("data.txt", ios::in); 
  fstream fst("data.txt", ios::in | ios::out);

关闭文件

使用成员函数close,如:

代码语言:javascript
复制
f.close();

读写操作

读取文件

读取一行:

代码语言:javascript
复制
infile.getline(data, 100);
infile >> data; 

在 C++ 编程中,使用流提取运算符( >> )从文件读取信息,就像使用该运算符从键盘输入信息一样。唯一不同的是,在这里使用的是 ifstream 或 fstream 对象.

写入文件

写入一行:

代码语言:javascript
复制
outfile << data << endl;

使用流插入运算符( << )向文件写入信息.

文件指正位置

代码语言:javascript
复制
// 定位到 fileObject 的第 n 个字节(假设是 ios::beg)
fileObject.seekg( n );
 
// 把文件的读指针从 fileObject 当前位置向后移 n 个字节
fileObject.seekg( n, ios::cur );
 
// 把文件的读指针从 fileObject 末尾往回移 n 个字节
fileObject.seekg( n, ios::end );
 
// 定位到 fileObject 的末尾
fileObject.seekg( 0, ios::end );

应用实例

代码语言:javascript
复制
int main() {
    fstream picture_fp, rar_fp,output_fp;
    char data;
    string data2;
    char picture_filename[50], rar_filename[50], output_filename[50];
    cout << "Please input the picture name :" << endl;
    cin>>picture_filename;
    cout << "Please input the rar file name :" << endl;
    cin >> rar_filename;
    cout << "Please input the output file name :" << endl;
    cin >> output_filename;

    picture_fp.open(picture_filename, ios::in|ios::binary);
    if (!picture_fp.is_open()) {
        cout << "打开失败" << endl;
    }
    rar_fp.open(rar_filename, ios::in | ios::binary);
    if (!rar_fp.is_open()) {
        cout << "打开失败" << endl;
    }
    output_fp.open(output_filename, ios::out | ios::binary);
    while (!picture_fp.eof())
    {
        data=picture_fp.get() ;//读一个字符
        //picture_fp >> data2;//读一行
        output_fp << data;
    }
    picture_fp.close();
    while (!rar_fp.eof())
    {
        data=rar_fp.get() ;//读一行
        output_fp << data;
    }    
    rar_fp.close();
    output_fp.close();

    system("pause");
}

参考

c++文件读写操作 C++ 文件和流

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • fstreaml类
    • 打开文件
    • 关闭文件
    • 读写操作
      • 读取文件
        • 写入文件
        • 文件指正位置
        • 应用实例
        • 参考
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档