简体   繁体   中英

saving/writing time to txt file in C++

I wanted to save the time into the existing txt file so that I can know when this particular record is added..I have this code to auto detect the time

time_t Now1;
struct tm * timeinfo;
char time1[20];
time(&Now1);
timeinfo = localtime(&Now1);
strftime(time1, 20, "%d/%m/%Y %H:%M", timeinfo);
Passports.Record_Added_On = time1;
cout << "\n\nRecord Added On: " << Passports.Record_Added_On;

code of reading the txt file:

fs = new fstream(Passports_FILE_NAME, ios::in | ios::out | ios::binary);
            if (!fs)
            {
                cout << "\n Can't open or create '" << Passports_FILE_NAME << "' file" << "\n";
                system("pause");
                break;
            }
            recs_num = -1;
            while (fs->read((char *)&Passports, sizeof(Passports)))
            {
                recs_num++;
                if (Passports.ID == id && !Passports.Deleted)
                break;
            }
            if (fs->eof()) //if (the record is not in the file || it's there but it's Deleted)
            {
                cout << "\nThe specific passports record does not exists in the file.";
                closeFile(fs);
                cout << "\n\nExit\n";
                return 0;
            }

it worked fine even when I display..however when I closed the program and open it again.. it shows weird characters like this or sometimes crashes..can anyone help me on this and explain what is the reason behind it?

在此处输入图片说明

You cannot initialize non POD objects ( like std::string class ) from memory. This leads to crashes because class does not know it is initialized. There is no guarantee that all class members where properly initialized from this code. Suppose that there was some class member which was pointer to some memory, allocated for you data. You saved it to file, then run your application again to load it. Then the pointer gets the same numeric value, but there is no more memory which he was pointing at. The memory must be allocated by OS, after OS function call, which was not called in our case. So next time you try to use this badly initialized class object - it crashed because it tries to work with memory which does not belongs to your application. To fix this crash you should parse the file contents properly and then fill your Passports record accordingly. For example:

int int_value;
std::string string_value;
fs >> int_value >> string_value;

after that you can initialize your object:

Passports.ID = int_value;
Passports.Name = string_value;

etc. The same way you should use to save data to the file ( this is called serialization, i recommend you search more on the topic ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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