J
John Smith
I want to open text files for input and output. The input file is
read and some processing is done to its contents. The processed
text is then written to the output file. The output file position
is reset, it is read from the top and some statistics are compiled.
The output file must initially be empty for each run of the
program. But, if I open the output file in "r+" mode to allow
both read and update, the contents of the file from the previous
run are preserved -- not what I want. I ended up with this code:
/* create the output file or
delete its contents if it exists */
if((outfile = fopen("fatext.txt", "w"))==NULL)
{
fprintf(stderr,"can't open fatext.txt in ""w"" mode\n");
exit(EXIT_FAILURE);
}
fclose(outfile);
if((infile = fopen(argv[1], "r"))==NULL)
{
fprintf(stderr,"can't open %s\n", argv[1]);
exit(EXIT_FAILURE);
}
/* reopen output file for read and update */
if((outfile = fopen("fatext.txt", "r+"))==NULL)
{
fprintf(stderr,"can't open fatext.txt in ""r+"" mode\n");
exit(EXIT_FAILURE);
}
This works, but it looks pretty ugly to me. Is there a better way?
JS
read and some processing is done to its contents. The processed
text is then written to the output file. The output file position
is reset, it is read from the top and some statistics are compiled.
The output file must initially be empty for each run of the
program. But, if I open the output file in "r+" mode to allow
both read and update, the contents of the file from the previous
run are preserved -- not what I want. I ended up with this code:
/* create the output file or
delete its contents if it exists */
if((outfile = fopen("fatext.txt", "w"))==NULL)
{
fprintf(stderr,"can't open fatext.txt in ""w"" mode\n");
exit(EXIT_FAILURE);
}
fclose(outfile);
if((infile = fopen(argv[1], "r"))==NULL)
{
fprintf(stderr,"can't open %s\n", argv[1]);
exit(EXIT_FAILURE);
}
/* reopen output file for read and update */
if((outfile = fopen("fatext.txt", "r+"))==NULL)
{
fprintf(stderr,"can't open fatext.txt in ""r+"" mode\n");
exit(EXIT_FAILURE);
}
This works, but it looks pretty ugly to me. Is there a better way?
JS