-1

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.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
PinkFloyd
  • 2,103
  • 4
  • 28
  • 47

2 Answers2

0

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.

Community
  • 1
  • 1
Alexey Frunze
  • 61,140
  • 12
  • 83
  • 180
  • ok thanks, that's what i thought... but is there a way to fread a file starting from the end then ? I could fwrite my summary at the end... – PinkFloyd Feb 26 '13 at 09:22
  • Set the file position with `fseek()` and then do `fread()` or `fwrite()` there. You'll need to open the file as binary, not as text for `fseek()` to work. Also, note how the file size can be determined, see `fsize()` in my answer by the link given. – Alexey Frunze Feb 26 '13 at 09:24
  • wonderful ! thanks for your help ! it's the first time that i post something on this forum, the speed of your answers is amazing ! – PinkFloyd Feb 26 '13 at 09:27
0

It is not possible to insert data before a file (without rewriting the whole file).

It is possible to overwrite some bytes at any point within the file. For this to implement your needs, the original file would have to have some bytes reserved—perhaps at the beginning—for later overwriting.

FILE *f = fopen ("thefile", "r+");  // opens for read and write, positioned at beginning
if (!f)  error_message();
size_t n = fwrite ("newdata", 1, 7, f);  // overwrite first 7 bytes
if (n != 7)  error_message();
fclose (f);
wallyk
  • 56,922
  • 16
  • 83
  • 148
  • yeah ! the thing is that i don't know the size of my summary... it will change all the time... so i can't reserve some bytes – PinkFloyd Feb 26 '13 at 09:23