E
E
Evgeny Yakushov2020-04-20 00:12:20
C++ / C#
Evgeny Yakushov, 2020-04-20 00:12:20

How to write and then read a structure from a binary file?

The essence is this, I write ala "Archiver", the essence is this, there is a structure:

struct File {
      char *fileName;
      char *fileContent;
      unsigneв int fileSize;
}


Then I start processing the file that the user enters:
PS: {I apologize right away, there will be a screenshot, I can’t capture text from the virtual machine
Kst, yes, I write in C under Linux.}

5e9cbba5029bc098161653.png

I determine the size of the file that is input, after which I allocate memory for a VARIABLE structure, so that later I can fread the contents of the file into this variable, save the entire structure to a file. For some reason, the binary file is smaller than the original, although there is a structure. Ref. the file is 13 bytes "Hello world!", and the binary is somewhere around 6-7 bytes, I don't understand why.

And how then to read this structure, if I allocated memory separately for the contents?
I tried to allocate memory for the structure in the form struct File *test = malloc(struct File) and read the file fread(test, FILE_SIZE, 1, FILE), but it gives an error, I can’t figure out how to read the file? But I still have a feeling that I'm doing the wrong entry in the binary, about the fact that I allocate memory separately for the variable yet.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
maaGames, 2020-04-20
@maaGames

There is no VARIABLE structure, the size of all data types is fixed at compile time. Memory must be allocated separately for each field of the structure, and each field will have to be saved / loaded separately. Those. in the file you write "fileName size", "fileName bytes", "fileContent size", "fileContent bytes". I’ll note right away that unsigned int for the file size limits the file size to 4 gigabytes, it’s better to use int64_t right away (I don’t know how it is customary to call it in C).
For reading / writing, you need to open it in binary form (for this task), and not in text.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question