Home > Blockchain >  How to insert a fixed amount of positions in a binary file?
How to insert a fixed amount of positions in a binary file?

Time:11-20

I need to insert data in a binary file in a way that every insertion is a block of 100 positions, for example. Since I know where it starts, I could easily use fseek/seekg to access elements 0 * 100, 1 * 100, 2 * 100,... n * 100. So how could I guarantee that every insertion ends in a position k * 100?

Or, alternatively, is it possible that I can add registers to an file in a way that I can iterate over them as if they were a array?

CodePudding user response:

File systems are not generally written to allow arbitrary insertions. At a minimum you will need to read the file contents after the point at which you wish to write, write your insert then write back the saved data. More typically you create a new temporary file, write the preceding contents, new contents then following contents, and only after the new file is completely written delete the old file and rename the new to have the original file's name. This is done so that the file is certain to always have valid contents even if something happens to your program or even the computer itself in the middle of the operation.

Some file systems do have the ability to write very specific inserts, but only at sizes much larger than 100 bytes. When this ability is present it will only work in certain powers of 2 sizes and offsets.

CodePudding user response:

The loop variable i is not the value you want to write. You want to write the value i instead.

{
    fwrite(&i,sizeof(i),1,fp);
}

should be

{
    fwrite(&i,sizeof(int),1,fp);
}

In your code, you are writing the value of the loop variable, which is always 0 (only one byte written). You probably want to write the value i instead.

  • Related