栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++学习日志46-----二进制读写、文件打开模式、随机访问文件

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++学习日志46-----二进制读写、文件打开模式、随机访问文件

目录
  • 一、二进制读写
  • 二、文件打开模式
  • 三、随机访问文件


一、二进制读写
#include
#include
#include
#include
namespace fs = std::filesystem;

int main()
{
    namespace fs = std::filesystem;
    using io = std::ios;

    fs::path p{ "array.dat" };
    //创建二进制输出流
    std::fstream out{ p,io::out | io::app };

    //判断流是否成功打开 省略

    //将一个整形数组的内容输出到二进制文件中
    std::array a{ 21L,42L,63L };
    std::streamsize size = a.size() * sizeof(a[0]);
    out.write(reinterpret_cast(&a[0]), size);

    //以读取模式重新打开二进制文件,或者将文件光标定位到文件头fsteam::seekg()
    out.close();
    out.open(p, io::in);

    //从二进制流中读入一个整数并显示到品目撒谎那个
    auto x{ 0L };
    out.read(reinterpret_cast(&x), sizeof(x));
    std::cout << x << std::endl;

    std::cin.get();


    return 0;
}


结果如上图所示。

二、文件打开模式
#include
#include
#include
namespace fs = std::filesystem;

int main()
{
    using fo = std::ios;
    fs::path p1{ "city1.txt" }, p2{ "city.txt" };

    //创建两个输出文件流,分别为app和trunc模式
    std::ofstream out1{ p1,fo::out | fo::app };  //追加模式
    std::ofstream out2{ p2,fo::out | fo::trunc };   //trunc 每次打开会清除内容

    //从键盘读入字符,输出到两个文件流中
    char c;  
    while (!std::cin.get(c).eof())
    {
        out1.put(c);
        out2.put(c);
    }
    //关闭文件流
    out1.close();
    out2.close();

    //读模式打开两个IO文件流,期中一个使用ate模式
    std::fstream in1{ p1,fo::in };
    std::fstream in2{ p2,fo  ::in | fo::ate };  //ate模式,每次打开,光标放在最后

    //输出两个文件的内容
    std::cout << p1 << std::endl;
    while (!in1.get(c).eof())
    {
        std::cout << c;
    }
    std::cout << p2 << std::endl;
    while (!in2.get(c).eof())
    {
        std::cout << c;
    }

    //关闭IO文件流
    in1.close();
    in2.close();

    std::cin.get();

    return 0;
}


注意这里需要ctrl+z 结束输入。

三、随机访问文件
#include
#include
#include
#include
#include

namespace fs = std::filesystem;
using std::wcout;
using std::endl;
using std::fstream;
int main()
{
    //任务1:在文件中存2个long long int 和“hello world”字符串
    fs::path p{ "test.dat" };
    fstream file{ p,std::ios::out | std::ios::in | std::ios::trunc };

    auto x{ 12LL }, y{ 24LL };
    char str[]{ "Hello World" };

    file.write(reinterpret_cast(&x), sizeof(x));
    file.write(reinterpret_cast(&y), sizeof(long long int));

    file.write(str, sizeof(str));

    //任务2:从文件中读取Hello字符串
    char buf[100]{ 0 };

    file.seekg(2 * sizeof(long long int), std::ios::beg);
    file.read(buf, 5);

    std::cout << buf << std::endl;
    return 0;
}


结果如上图所示。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/862673.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号