简体   繁体   English

c++ 在二进制文件中以字节形式写入日期并在同一视图中读取

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

I have multiple dates in yyyy-mm-dd format, which I need to write in a binary file as bytes and then read them in the same format.我有多个yyyy-mm-dd格式的日期,我需要将其作为字节写入二进制文件,然后以相同的格式读取它们。 Here is the method I have for writing the file (but seems it is not fully correct):这是我编写文件的方法(但似乎不完全正确):

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

Method for reading the file:文件读取方法:

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

When trying to read, I'm getting this output in the console:尝试阅读时,我在控制台中收到此 output:

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

It seems, when I am trying to read the file, I am getting char's but not in the same format that I need.看起来,当我尝试读取文件时,我得到的是字符,但不是我需要的格式。

Can someone help with fixing my issue?有人可以帮助解决我的问题吗?

I noticed that in your code you use numbers instead of chars to represent the year (eg char yearArr[] = {2, 0, 2, 2}; ).我注意到在您的代码中您使用数字而不是字符来表示年份(例如char yearArr[] = {2, 0, 2, 2}; )。 Is that by design?这是设计使然吗? I would prefer to use char yearArr[] = {'2', '0', '2', '2'};我更愿意使用char yearArr[] = {'2', '0', '2', '2'}; In fact, I would convert everything to char, so that I can read/write to the file using char.事实上,我会将所有内容都转换为 char,这样我就可以使用 char 读取/写入文件。

Another observation I made is that your read char array ( char inputArr[8]; ) does not have a null terminator (eg inputArr[8] = '\0'; ).我所做的另一个观察是,您读取的字符数组 ( char inputArr[8]; ) 没有 null 终止符(例如inputArr[8] = '\0'; )。 This should eliminate the extra garbage characters at the end.这应该消除最后多余的垃圾字符。

There are several questions I still have about your code but here's a simpler but similar problem that you can use as a guide:关于您的代码,我仍然有几个问题,但这里有一个更简单但类似的问题,您可以将其用作指南:

#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] = '\0';
    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';
    }
}

The output of this code: Binary file: 2022-05-04此代码的 output: Binary file: 2022-05-04

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM