How to write the first line in a text file when opened file as 'a+'

I'am having issues rewriting the first line of a text file when I open the file as 'a+'. Example:
file = fopen('example.txt','a+'); frewind(file); fprintf(file,'%f %u %u',version, numlines, newChecksum); fclose(file);
The objective of the code is to add update the information from the first line of the file. The problem is that when I do the fprintf() it writes the info. at the end of the file not at the beginning where the file pointer is currently located after the frewind(). I have also tried the fseek. Both frewind and fseek work because if I use the command fgets() to get the first line it dose get the info. located at the beginning to the file.

 Accepted Answer

Why not use 'w' instead of 'a+'?

3 Comments

Because 'w' erases the file. I need to keep the file as it was because I am adding new info. at the end of the file periodically. The file is a log file so it increments its size very often. I only want to read my header file to only check the checksum and update it once I add the new info. on too the log file. I fear that if I extract the file every time and rewrite it the program will eventually slow down.
AFAIK: The only way to rewrite the first line of a text file without touching the rest is with memmapfile. However, you must not change the number of bytes.
That works like a charm, thank very much. That solve the problem because the header won't change size.
Kudos per isakson, I'am very great full.

Sign in to comment.

More Answers (0)

Asked:

on 9 Oct 2013

Commented:

on 9 Oct 2013

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!