A
A
armadillo-cld2020-07-22 19:31:43
C++ / C#
armadillo-cld, 2020-07-22 19:31:43

How to transfer the structure to a binary file so that it can read it without damaging the file?

Hello.
There is this code:

// Объявляю структуру
struct Settings {
int year;
char name[52];
};
..
long int filesize = 92672; // Приходиться контролировать размер файла =(
Settings s;
int fize = MAX_PATH;
char *filename = new char[size];
GetModuleFileNameA(NULL, filename, size); // Получаю путь к себе

ifstream file(filename, ios::binary);
file.seekg(filesize); // Ставлю указатель на конец файла
file.read((char*)&data, sizeof(Settings)); // Читаю внедрённую структуру
file.close(); // Закрываю

This is the binary itself.
And here is the file that implements the structure:
// Объявляю структуру 
struct Settings {
int year;
char name[52];
}
..
// Инициализирую переменные
Settings s;
s.year = 12;
strcpy(s.name, "Alesha");

// Внедряю
ifstream binaryfile("person.exe", ios::binary);
ofstream injected("person created.exe", ios::binary);

injected << binaryfile.stdbuf();
binaryfile.close();

injected.write((char*)&s, sizeof(Settings));
injected.close();


But this method has disadvantages:
1. You have to enter the file size in bytes, and if you enter large data, the file size will become larger than the entered one and garbage will be displayed.
2. Not working. For some reason if I add new variables. For example "charcar[52];" etc., then either empty lines or garbage will be displayed in the form *! @ (EU.

What to do? Is there some kind of "cross-platform" way? You need to transfer the data to a binary file somehow.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Mercury13, 2020-07-22
@armadillo-cld

Let's start with 2. Structures used as a file format should be used in application code with great care. If you want the format to expand, come up with a simple block format.
For 1, you have to use some kind of signature and find it in the file.
For example: after the actual EXE file comes the data, then the signature and the position of the data in the file. There is no signature or the offset is strange - so just paste all this rubbish at the end of the file. The signature is there and the offset is plausible - we go to the specified offset, write new data along with the new signature, and then truncate the file (in case the old data was longer).
By the way, self-extracting RAR and RARJPEG archives are based on this principle - only the signature at the beginning, and not at the end of the RAR data.
You also need to check in which encoding ifstream accepts data - UTF-8 or Win-1251. Starting with C++17, support for unicode filenames appeared, but I did not work with it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question