Search code examples
posixstandardsgnu

Behaviour of fwrite


I assume to have a file filled with data.

If I open this file in "r+" mode and seek to any non-EOF position and write one or more characters to this file, what would be the standard result?

  • In POSIX
  • In GNU
  • In DOS/Windows?

Would the following characters be overwritten or shifted?

If one needs an example this could be such a file:

File a.tx:

abcdefghijklmnopqrstuvwxyz

C code snippet:

FILE * f = fopen("a.tx", "r+");
fseek(f, 5, SEEK_SET);
char * str = "12";
fwrite(str, 1, 2, f); // this is just an example

Solution

  • This is a very very basic I/O behavior... and not related either to POSIX, GNU or DOS/Windows, it is just standard C.

    It will just write 12 at position 5 (start counting at 0), so writing 12 over fg. Beware that this may not be immediately visible in the file, since the write may be buffered; if you close or flush the file just after, then data will be surely written to the physical destination.

    There is generally no shifting (you mean inserting right?) available in operating systems, while you can view it as a basic functionality, inserting something into a file necessitate too much operations to be considered as a basic OS function.