首页 > 其他分享 >二进制读写文件

二进制读写文件

时间:2024-09-14 17:52:42浏览次数:3  
标签:文件 二进制 读写 readFile binaryWrite printf array data 34567668

提示:文章

文章目录

前言

前期疑问:
本文目标:


一、背景

这个文章主要是针对二进制文件的读写

大概会分为c语言对二进制文件读写和c++对二进制文件的读写

查找资料看到这篇文章:二进制文件的读写操作,文章是分别对整型变量、数组、字符串进行读写。我其实想得到是对混合的数据的读写,但是我突然想到可以将整型数据转成char型然后使用字符串写成二进制啊。没毛病,那么很长的字符串(大于1024)是怎么写入呢。可以试一下。

二、c语言读写二进制文件

2.1

二进制读写文件

#include <iostream>
#include <stdio.h>
#include <string.h>

struct BinaryWriteStruct
{
    char a;
    int b;
    float c;
    double d;
    char array[15];
    //std::string e;
    BinaryWriteStruct()
    {
        a = '0';
        b = 0;
        c = 0.0f;
        d = 0;
        memset(array, 0, sizeof(array));
    }
};

typedef BinaryWriteStruct BinaryWrite;

struct BinaryWriteStruct2
{
    char a;
    int b;
    float c;
    double d;
    char array[15];
};

typedef BinaryWriteStruct2 BinaryWrite2;

void BinaryWriteInteger()
{
    FILE* writeFile = fopen("E:\\writeInteger.txt", "wb");
    if (writeFile == nullptr) {
        printf("%s", "file open failed\n");
    }
    // 存储一个整型变量
    int a = -11; 	//-1的二进制:

    fwrite(&a, sizeof(int), 1, writeFile);
    fclose(writeFile);
}

void BinaryReadInteger()
{
    FILE* readFile = fopen("E:\\writeInteger.txt", "r");
    if (readFile == nullptr) {
        printf("%s", "file open failed\n");
    }
    // 存储一个整型变量
    int a = 0; 	//-1的二进制:

    fread(&a, sizeof(int), 1, readFile);
    printf("a:%d\n", a);
    fclose(readFile);
}

void BinaryWriteStruct()
{
    FILE* writeFile = fopen("E:\\writeStruct.txt", "wb");
    if (writeFile == nullptr) {
        printf("%s", "file open failed\n");
    }
    // 存储一个结构体变量
    BinaryWrite binaryWrite;
    
    binaryWrite.a = 'Q';
    binaryWrite.b = 1;
    binaryWrite.c = 2.1f;
    binaryWrite.d = 4;
    strcpy(binaryWrite.array, "hello world");
    //binaryWrite.e = "this ia a string";       //这边写入string会导致读不到正确的数据,fwrite是c函数,std::string是c++对象

    // 测试结构体,验证为什么BinaryWrite结构体不能定义时直接赋值初始化
    BinaryWrite2 binaryWrite2 = {'Q', 1, 2, 3, "test"};        //当结构体没有构造函数时可以这样初始化,有构造函数就要上述初始化方式

    fwrite(&binaryWrite, sizeof(BinaryWrite), 1, writeFile);
    fclose(writeFile);
}

void BinaryReadStruct()
{
    FILE* readFile = fopen("E:\\writeStruct.txt", "rb");            //这边不写"rb"会读不到数据
    if (readFile == nullptr) {
        printf("%s", "file open failed\n");
    }
    // 存储一个整型变量
    BinaryWrite binaryWrite;

    fread(&binaryWrite, sizeof(BinaryWrite), 1, readFile);
    printf("a:%c\n", binaryWrite.a);
    printf("b:%d\n", binaryWrite.b);
    printf("c:%f\n", binaryWrite.c);
    printf("d:%f\n", binaryWrite.d);
    printf("array:%s\n", binaryWrite.array);
    //printf("e:%s\n", binaryWrite.e.c_str());
    fclose(readFile);
}

void BinaryWriteString()
{
    char array[] = {
            "data:34567668-0-05678709886r434563212212225113e65r41325541235412344236544265344652344542365442356442653446"
            "5234465234464236544235644524423445243442344244234452344523442534452434524345243452434562434562344524345245"
            "454564544,data:34567668-0-05678709886r434563212212225113e65r4132554123541234423654426534465234454236544235"
            "6442653446523446523446423654423564452442344524344234424423445234452344253445243452434524345243456243456234"
            "4524345245454564544,data:34567668-0-05678709886r434563212212225113e65r413255412354123442365442653446523445"
            "4236544235644265344652344652344642365442356445244234452434423442442344523445234425344524345243452434524345"
            "62434562344524345245454564544,data:34567668-0-05678709886r434563212212225113e65r41325541235412344236544265"
            "3446523445423654423564426534465234465234464236544235644524423445243442344244234452344523442534452434524345"
            "243452434562434562344524345245454564544,data:34567668-0-05678709886r434563212212225113e65r4132554123541234"
            "4236544265344652344542365442356442653446523446523446423654423564452442344524344234424423445234452344253445"
            "2434524345243452434562434562344524345245454564544, end"};
    FILE* writeFile = fopen("E:\\writeString.nag", "wb");
    if (writeFile == nullptr) {
        printf("%s", "file open failed\n");
    }

    fwrite(array, sizeof(char), sizeof(array), writeFile);
    fclose(writeFile);
}
void BinaryReadString()
{
    FILE* readFile = fopen("E:\\writeString.txt", "rb");
    if (readFile == nullptr) {
        printf("%s", "file open failed\n");
    }
    char array[10000] = {'\0'};

    char tempStr[100] = {'\0'};
    int count = 0;
    while (!(feof(readFile) || ferror(readFile))) {
        fread(tempStr, sizeof(char), sizeof(tempStr), readFile);
        strcpy(array + 100 * count, tempStr);
        count++;
    }
    if (ferror(readFile)) {
        printf("file read fail\n");
    }
    fclose(readFile);
    printf("%s\n", array);
}

int main()
{
    // 二进制写入整型
    BinaryWriteInteger();
    BinaryReadInteger();
    // 二进制写入结构体
    BinaryWriteStruct();
    BinaryReadStruct();
    // 二进制写入字符串
    BinaryWriteString();
    BinaryReadString();
    return 0;
}

打印结果

a:-11
a:Q
b:1
c:2.100000
d:4.000000
array:hello world
data:34567668-0-05678709886r434563212212225113e65r4132554123541234423654426534465234454236544235644265344652344652344642
36544235644524423445243442344244234452344523442534452434524345243452434562434562344524345245454564544,data:34567668-0-05
678709886r434563212212225113e65r4132554123541234423654426534465234454236544235644265344652344652344642365442356445244234
45243442344244234452344523442534452434524345243452434562434562344524345245454564544,data:34567668-0-05678709886r43456321
2212225113e65r4132554123541234423654426534465234454236544235644265344652344652344642365442356445244234452434423442442344
52344523442534452434524345243452434562434562344524345245454564544,data:34567668-0-05678709886r434563212212225113e65r4132
554123541234423654426534465234454236544235644265344652344652344642365442356445244234452434423442442344523445234425344524
34524345243452434562434562344524345245454564544,data:34567668-0-05678709886r434563212212225113e65r4132554123541234423654
426534465234454236544235644265344652344652344642365442356445244234452434423442442344523445234425344524345243452434524345
62434562344524345245454564544, end

三、c++读写二进制文件

3.1

下面是c++二进制读写文件

void BinaryWriteStringByCpp()
{
    char array[] = {
            "data:34567668-0-05678709886r434563212212225113e65r41325541235412344236544265344652344542365442356442653446"
            "5234465234464236544235644524423445243442344244234452344523442534452434524345243452434562434562344524345245"
            "454564544,data:34567668-0-05678709886r434563212212225113e65r4132554123541234423654426534465234454236544235"
            "6442653446523446523446423654423564452442344524344234424423445234452344253445243452434524345243456243456234"
            "4524345245454564544,data:34567668-0-05678709886r434563212212225113e65r413255412354123442365442653446523445"
            "4236544235644265344652344652344642365442356445244234452434423442442344523445234425344524345243452434524345"
            "62434562344524345245454564544,data:34567668-0-05678709886r434563212212225113e65r41325541235412344236544265"
            "3446523445423654423564426534465234465234464236544235644524423445243442344244234452344523442534452434524345"
            "243452434562434562344524345245454564544,data:34567668-0-05678709886r434563212212225113e65r4132554123541234"
            "4236544265344652344542365442356442653446523446523446423654423564452442344524344234424423445234452344253445"
            "2434524345243452434562434562344524345245454564544, cpp end"};
    std::ofstream outputStream("E:\\writeStringByCpp.nag", std::ios::out | std::ios::binary);
    if (!outputStream.is_open()) {
        printf("file open failed\n");
    }
    outputStream.write(array, sizeof(array));
}

void BinaryReadStringByCpp()
{
    std::ifstream inputStream("E:\\writeStringByCpp.nag", std::ios::in | std::ios::binary);
    if (!inputStream.is_open()) {
        printf("file open failed\n");
    }
    std::stringstream inputStr;
    inputStr << inputStream.rdbuf();
    std::string str(inputStr.str());
    printf("%s\n", str.c_str());
}

int main()
{
    // c++二进制读写字符串
    BinaryWriteStringByCpp();
    BinaryReadStringByCpp();
    return 0;
}

打印信息

data:34567668-0-05678709886r434563212212225113e65r4132554123541234423654426534465234454236544235644265344652344652344642
36544235644524423445243442344244234452344523442534452434524345243452434562434562344524345245454564544,data:34567668-0-05
678709886r434563212212225113e65r4132554123541234423654426534465234454236544235644265344652344652344642365442356445244234
45243442344244234452344523442534452434524345243452434562434562344524345245454564544,data:34567668-0-05678709886r43456321
2212225113e65r4132554123541234423654426534465234454236544235644265344652344652344642365442356445244234452434423442442344
52344523442534452434524345243452434562434562344524345245454564544,data:34567668-0-05678709886r434563212212225113e65r4132
554123541234423654426534465234454236544235644265344652344652344642365442356445244234452434423442442344523445234425344524
34524345243452434562434562344524345245454564544,data:34567668-0-05678709886r434563212212225113e65r4132554123541234423654
426534465234454236544235644265344652344652344642365442356445244234452434423442442344523445234425344524345243452434524345
62434562344524345245454564544, cpp end

总结

未完待续

标签:文件,二进制,读写,readFile,binaryWrite,printf,array,data,34567668
From: https://blog.csdn.net/2301_77560238/article/details/142258303

相关文章

  • linux文件权限操作
    权限模型Linux的权限控制基于RBAC(RoleBasedAuthenticationControl)模型RBAC模型:基于角色的权限控制。资源:权限控制系统要保护的对象,在linux中就是文件和目录;权限:对资源的操作,包括读和写角色:对用户的分组。将同一类的用户划分到同一个用户组中,让他们具备相同的权限。......
  • 合并所有文件
    importosimportpandasaspdimportosimportshutildefclear_folder(folder_path):#检查文件夹是否存在ifnotos.path.exists(folder_path):print(f"文件夹{folder_path}不存在。")return#遍历文件夹中的所有文件和子文件夹forfilenam......
  • Python存储与读写二进制文件
    本文介绍了一种在Python中将Numpy数组转存为一个紧凑的二进制格式的文件,及其使用内存映射的形式进行读取的方案。一个二进制的数据流,不仅可以更加方便页形式的内存映射,相比于传统的Numpy单精度浮点数数组还有一个可哈希的特性。总体来说是一个对于高性能计算十分友好的存......
  • GGUF大模型文件格式
    GGUF大模型文件格式https://www.datalearner.com/blog/1051705718835586 大语言模型的开发通常使用PyTorch等框架,其预训练结果通常也会保存为相应的二进制格式,如pt后缀的文件通常就是PyTorch框架保存的二进制预训练结果。但是,大模型的存储一个很重要的问题是它的模型文件巨......
  • 实现 Excel 文件导入到向量数据库(Milvus),并支持 先查询知识库(Milvus),然后再查询大模型(Ol
    为了实现Excel文件导入到向量数据库(Milvus),并支持先查询知识库(Milvus),然后再查询大模型(Ollama)的功能,以下是具体的实现步骤:1.导入Excel数据到向量数据库(Milvus)首先,您需要将Excel文件中的数据向量化,并将这些向量导入到Milvus数据库中。可以使用pandas读取Excel文件,使用......
  • src/pyaudio/device_api.c:9:10: fatal error: portaudio.h: 没有那个文件或目录
    (venv)shgbitai@shgbitai-C9X299-PGF:~/pythonworkspace/ai-accompany$pipinstallpyaudiosounddeviceCollectingpyaudioDownloadingPyAudio-0.2.14.tar.gz(47kB)━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━47.1/47.1k......
  • 鼓励读写结合
    在语文学科的教学中,教师要以培养学生的语文核心素养为切入点,以古诗词为载体设计写作环节,强化学生的古诗词阅读体验,引导学生将阅读体验写下来,提高学生写作的主动性和积极性,开发学生思维。以《枫桥夜泊》这首古诗为例,教师可组织开展“古诗新写”的教学活动,引导学生在阅读《枫桥夜泊......
  • 10款功能强大的电脑加密软件排行榜!企业文件加密软件推荐
    在当今数字化时代,数据安全已成为企业运营的重中之重。无论是个人用户还是企业用户,都需要确保其重要文件和数据的安全性。电脑加密软件作为一种有效的数据保护工具,能够帮助用户加密敏感信息,防止数据泄露和未经授权的访问。1.安秉网盾这是一款专门为满足企业需求设计的加密软......
  • python https 下载文件
    同步下载defdownload_file_block(url:str,file_path:str):logging.basicConfig(level=logging.DEBUG)log=logging.getLogger('requests.packages.urllib3')log.setLevel(logging.DEBUG)log.propagate=TrueclassDebugAdapter(HTTPAd......
  • 无数据备份和无归档文件时,使用bbed修改数据文件头的SCN,强制打开数据库的方法
    在数据库运维中经常会遇到某个数据文件的SCN与其他文件的SCN不一致(如offline后或者异常断电),如果归档日志被删除了,导致datafile不能recover,数据库不能打开情况,这时候我们需要借助bbed修改datafileheader的scn与其他datafile的headerscn一致,然后recoverdatafile。一、问题产生......