C++/C saves the bin file according to the time

background

In the process of Linux application programming, using C++ or C language to save and read bin files is a relatively common requirement. Here is a detailed record of using C++ to save the bin file, and it can also be implemented in C language.

the code

C++/C language saves the bin file function, which can also be used in C++

Correct write returns 0, error returns -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;
}

For the production of file paths, a string related to time when the file is camped

First get the current time, and then improve saveFilePath according to the required naming format

writeBin function call, store randomif_buf data to a local file

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));

The header files that need to be included here are as follows:

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

For the reading of bin files, the following functions can be used to realize that the reading is correct and returns 0, and the reading error returns -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;
}

The bin file stored during actual use is shown in the figure below

It can be clearly seen that the naming format of the file is correct, which is the implementation of our code above.

The bin file is viewed with vscode, and a plug-in for the bin file needs to be installed

Binary Viewer

Search as shown in the figure below, the plug-in can be installed 

The specific use is shown in the figure below

Select the bin file to be viewed, right-click to select the hexadecimal viewing method, and all the data can be displayed, which is more convenient, especially in ubuntu. Many tools in windows can view bin files, and ubuntu is also a good way. 

Guess you like

Origin blog.csdn.net/li171049/article/details/131133664