c ++将日期作为二进制文件中的字节写入并在同一视图中读取

c++ write date as bytes in binary file and read in same view

我有多个 yyyy-mm-dd 格式的日期,我需要将其作为字节写入二进制文件,然后以相同的格式读取它们。这是我写文件的方法(但似乎不完全正确):

fstream f("binaryOut.bin", ios::out | ios::binary);
string dateString;
char arr[4];
char dateArray[8];
for (int i = 0; i < amountOfDates; i++)
{
    stringstream str;
    char yearArr[] = {2, 0, 2, 2};
    strncpy_s(dateArray, yearArr, 4);
    int year = 2022;
    char generatedDay = 0, generatedMonth = 0;
    generatedMonth = getGeneratedValue(1, 12);
    dateArray[4] = '-';
    dateArray[5] = generatedMonth;
    generatedDay = getGeneratedValue(1, 31);
    dateArray[6] = '-';
    dateArray[7] = generatedDay;
    str >> dateString;
    strcpy_s(arr, dateString.c_str());
    f.write(dateArray, 8);
}
f.close();

读取文件的方法:

fstream f("binaryOut.bin", ios::in | ios::binary);
char inputArr[8];
for (int i = 0; i < amountOfDates; i++)
{
    f.read(inputArr, 8);
    for (int i = 0; i <= 8; i++)
    {
        if (isdigit(inputArr[i]))
        {
            cout << inputArr[i] - '0';
        }
        else if (inputArr[i] == '-')
        {
            cout << inputArr[i];
        }
        else
        {
            cout << inputArr[i] << static_cast<int>(inputArr[i]);
        }
    }
    cout << endl;
}

尝试阅读时,我在控制台中得到以下输出:

☻20■-2■-2-♠6-↨23╠-52
☻20■-2■-2-♂11-7╠-52
☻20■-2■-2-♠68╠-52
☻20■-2

似乎,当我尝试读取文件时,我得到的是字符,但不是我需要的格式。

有人可以帮助解决我的问题吗?

我注意到在您的代码中您使用数字而不是字符来表示年份(例如 char yearArr[] = {2, 0, 2, 2};)。这是设计使然吗?我更愿意使用 char yearArr[] = {'2', '0', '2', '2'}; 实际上,我会将所有内容都转换为 char,这样我就可以 read/write 使用 char.

到文件

我的另一个观察是您读取的字符数组 (char inputArr[8];) 没有空终止符(例如 inputArr[8] = '[=14=]';)。这应该消除最后多余的垃圾字符。

关于您的代码,我仍然有几个问题,但这里有一个更简单但类似的问题,您可以将其用作指南:

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <time.h>

void WriteToBinaryFile();
void ReadFromBinaryFile();
void GetYear(char*);
void GetMonth(char*);
void GetDay(char*);

int main()
{
    srand(time(0));
    WriteToBinaryFile();
    ReadFromBinaryFile();

    return 0;
}

void WriteToBinaryFile()
{
    std::ofstream binary_file("binaryOut.bin", std::ios::out | std::ios::binary);
    char date[10] = { 'Y', 'Y', 'Y', 'Y', '-', 'M', 'M', '-', 'D', 'D' };

    GetYear(date);
    GetMonth(date);
    GetDay(date);

    if (!binary_file)
    {
        std::cout << "Can't open binary file for write" << std::endl;
        return;
    }

    binary_file.write(date, sizeof(date) / sizeof(char));
    binary_file.close();

    if (!binary_file.good())
    {
        std::cout << "Error occurred during write" << std::endl;
        return;
    }
}

void ReadFromBinaryFile()
{
    std::ifstream binary_file("binaryOut.bin", std::ios::out | std::ios::binary);

    if (!binary_file)
    {
        std::cout << "Can't open binary file for read" << std::endl;
        return;
    }

    char date[10];

    binary_file.read(date, sizeof(date) / sizeof(char));
    binary_file.close();

    if (!binary_file.good())
    {
        std::cout << "Error occurred during read" << std::endl;
        return;
    }

    date[10] = '[=10=]';
    std::cout << "Binary file: " << date << std::endl;
}

void GetYear(char* date)
{
    const char year[] = { '2', '0', '2', '2' };
    date[0] = year[0];
    date[1] = year[1];
    date[2] = year[2];
    date[3] = year[3];
}

void GetMonth(char* date)
{
    int month = (std::rand() % 11) + 1;

    if (month > 9)
    {
        int first_digit = month % 10;
        int second_digit = month / 10;
        date[5] = first_digit + '0';
        date[6] = second_digit + '0';
    }
    else
    {
        date[5] = '0';
        date[6] = month + '0';
    }
}

void GetDay(char* date)
{
    int day = (std::rand() % 31) + 1;

    if (day > 9)
    {
        int first_digit = day % 10;
        int second_digit = day / 10;
        date[8] = first_digit + '0';
        date[9] = second_digit + '0';
    }
    else
    {
        date[8] = '0';
        date[9] = day + '0';
    }
}

这段代码的输出:Binary file: 2022-05-04