The "rb"
mode opens the file positioned at the start; the initial fseek()
is redundant.
The second open with "ab"
opens the file for writing in append mode. All writes will occur at the end of the file, regardless of what fseek()
operations you do beforehand.
You could sensibly use mode "rb+"
to open the file once for both reading and writing:
if ((f = fopen(argv[2], "rb+")) != 0)
{
char *data = calloc(2*1024+512, 1); // Missing error check
fread(data, 1, 2*1024+512, f); // Missing error check
// Modify data?
fseek(f, 0, SEEK_SET);
fwrite(data, 1, 446, f);
fseek(f, 512, SEEK_SET);
fwrite(((char*)data)+512, 1, 2*1024, f);
fclose(f);
}
The code should check that the calloc()
succeeds before using data
; it should also error check the fread()
to be sure it got the expected data. Presumably, something in the middle will modify the data read from the file.
ISO/IEC 9899:2011 (the current C standard) has this to say about the modes for fopen()
— and the previous standards said much the same except for the x
flag, which is new in C11:
§7.21.5.3 The
fopen
function¶3 The argument
mode
points to a string. If the string is one of the following, the file is open in the indicated mode. Otherwise, the behavior is undefined.271)
r
open text file for readingw
truncate to zero length or create text file for writingwx
create text file for writinga
append; open or create text file for writing at end-of-filerb
open binary file for readingwb
truncate to zero length or create binary file for writingwbx
create binary file for writingab
append; open or create binary file for writing at end-of-filer+
open text file for update (reading and writing)w+
truncate to zero length or create text file for updatew+x
create text file for updatea+
append; open or create text file for update, writing at end-of-filer+b
orrb+
open binary file for update (reading and writing)w+b
orwb+
truncate to zero length or create binary file for updatew+bx
orwb+x
create binary file for updatea+b
orab+
append; open or create binary file for update, writing at end-of-file271) If the string begins with one of the above sequences, the implementation might choose to ignore the remaining characters, or it might use them to select different kinds of a file (some of which might not conform to the properties in §7.21.2).