Writing text output to a file
We've used fgets() to 'get' a line of text (a string) from a file;
we similarly use fputs() to 'put' (write) a line of text.
The file pointer passed to fputs() must previously have been opened for
writing or appending.
Copying a text file using file pointers
We now have all the functions necessary to copy one text file to another,
one line line at a time:
#include <stdio.h>
#include <stdlib.h>
void copy_text_file(char destination[], char source[])
{
FILE *fp_in = fopen(source, "r");
FILE *fp_out = fopen(destination, "w");
// ENSURE THAT OPENING BOTH FILES HAS BEEN SUCCESSFUL
if(fp_in != NULL && fp_out != NULL) {
char line[BUFSIZ];
while( fgets(line, sizeof line, fp_in) != NULL) {
if(fputs(line, fp_out) == EOF) {
printf("error copying file\n");
exit(EXIT_FAILURE);
}
}
}
// ENSURE THAT WE ONLY CLOSE FILES THAT ARE OPEN
if(fp_in != NULL) {
fclose(fp_in);
}
if(fp_out != NULL) {
fclose(fp_out);
}
}
|
CITS2002 Systems Programming, Lecture 7, p8, 12th August 2024.
|