C++/C按照时间命名保存bin文件

背景

在Linux应用编程过程中,使用C++或者C语言保存、读取bin文件是比较常见的需求。这里详细记录一下使用C++保存bin文件,也可以使用C语言实现。

代码

C++/C语言保存bin文件函数,C++中也能使用

正确写入返回0,错误返回-1

// C 保存bin文件
int writeBin(char *path, unsigned char *buf, int size)
{
    FILE *outfile;

    if ((outfile = fopen(path, "wb")) == NULL)
    {
        printf("\nCan not open the path: %s \n", path);
        return -1;
    }
    fwrite(buf, sizeof(unsigned char), size, outfile);
    fclose(outfile);
    return 0;
}

针对文件路径的制作,文件露营时一个与时间有关的字符串

首先获取当前时间,然后根据需要的命名格式,完善saveFilePath

writeBin函数调用,将randomif_buf数据存储到本地文件

time_t timep;
time (&timep);
char saveFilePath[128];
memset(saveFilePath, 0, sizeof(saveFilePath));
strftime(saveFilePath, sizeof(saveFilePath), "./%Y-%m-%d_%H_%M_%S_usb.bin",localtime(&timep));

writeBin(saveFilePath, randomif_buf, sizeof(randomif_buf));

这里需要包含的头文件如下:

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

针对bin文件的读取,可以采用如下函数实现,读取正确返回0,读取错误返回-1

int readBin(char *path, char *buf, int size)
{
    FILE *infile;

    if ((infile = fopen(path, "rb")) == NULL)
    {
        printf("\nCan not open the path: %s \n", path);
        return -1;
    }
    fread(buf, sizeof(char), size, infile);
    fclose(infile);
    return 0;
}

实际使用过程中存储的bin文件如下图所示

明显可以看出来文件的命名格式时正确的,是上述我们代码的实现方式。

bin文件使用vscode查看,需要安装一个bin文件的插件

Binary Viewer

如下图 所示搜索,该插件,安装即可 

具体使用如下图所示

选中需要查看的bin文件,右击选择16进制查看的方式,所有的数据都可以显示出来,还是比较方便,尤其是在ubuntu中。window中很多工具可以查看bin文件,ubuntu这也是个好方式。 

猜你喜欢

转载自blog.csdn.net/li171049/article/details/131133664
今日推荐