Search code examples
cfwritefread

C fread fwrite at the beginning of a file


I would like to know if it's possible to write data at the beginning of a file using frwite. Let me be more precise, I open a file using fopen then I write some data to it with write. Just before closing the file I like to write a little summary of what is inside the file. I suppose that the best place to put this summary is at the beginning of the file. So when i open the file later, I can read first the summary and then the data.

actually the place where I put the summary doesn't matter as long as I can read it first when I open the file.


Solution

  • If you're asking about whether or not you can use fwrite(), putc(), fprintf() and the like to insert information at the beginning of a non-empty file, the answer is no, you can't do that.

    You can either overwrite data or append data.

    If you want to insert, you need to check with your OS APIs to see if there's a special function for that and if there isn't, you need to create another file, write the summary into it and then write the contents of the original file. Another option is to manually move the data to free up enough space at the beginning of the file, so the summary can be written there.

    You can read a text file backwards, if you really want it.