INF: Appending to a CTRL+Z Terminated File with fopen()

ID Number: Q76943

4.00 5.00 5.10 6.00 6.00a 6.00ax

MS-DOS

Summary:

When appending to a stream file that is terminated with the CTRL+Z

end-of-file marker, use "a+" as the mode type for the fopen()

function. This will allow for both reading and writing of the file.

More Information:

When a file is opened with the "a+" mode, the CTRL+Z character is

deleted at the end of the file. Files opened with the "a" mode for

appending in write-only mode will not have the end-of-file marker

removed.

The end-of-file marker must be removed to view the entire file after

appending. The "a+" is required to allow MS-DOS to read the file to

locate the end-of-file marker and overwrite it with appended data.

Using the "a" type prevents MS-DOS from reading the file; therefore,

MS-DOS can't find the end-of-file marker for overwriting. Such editors

as Edlin and WordStar ignore all characters after the first CTRL+Z in

a file. Consequently, if the text is appended after the CTRL+Z, it

will not be viewable by the above editors or by the MS-DOS TYPE

command.

Note: ANSI editors, such as Programmer's WorkBench (PWB), cannot allow

a file to be closed without a carriage return-linefeed sequence at the

end of the file. If an explicit CTRL+Z is added to the end of the

file, and the file is saved, a CR/LF will be added to the end, causing

the append example (below) to fail, because the CTRL+Z is no longer at

the end of the file.

The following code demonstrates this:

Sample Code

-----------

#include <stdio.h>

#include <time.h>

void main(void)

{

FILE *fp;

int num;

time_t system_time;

fp = fopen("out.dat","a"); /* change to "a+" to fix */

time(&system_time); /* to demonstrate last append */

num = fprintf(fp, "Writing to file at %s\n",

ctime(&system_time));

num = fclose(fp);

}

Additional reference words: 4.0 4.00 5.0 5.00 5.1 5.10 6.0 6.00 6.0a

6.00a 6.0ax 6.00ax