Writing to Files Using fwrite
This function has the same four arguments to fread:
The first is a char * variable and is what you want to write into a file.
The second is the size of char, i.e. 1.
The third is the number of characters to write - this does come into effect when passing a char * as opposed to a char array.
Finally, the last argument is the FILE pointer to the file to write to.
This example is saved as file.c - it opens file.c for reading, and copies the content into file2.c
Afterwards, it'll open file2.c and display the source code on the screen, including the comments!
Notice I used two FILE pointers - one for the reading, the other for the writing.
#include <stdio.h>
int main() {
FILE *sourceFile;
FILE *destinationFile;
char *buffer;
int n;
sourceFile = fopen("file.c", "r");
destinationFile = fopen("file2.c", "w");
if(sourceFile==NULL) {
printf("Error: can't access file.c.\n");
return 1;
}
else if(destinationFile==NULL) {
printf("Error: can't create file for writing.\n");
return 1;
}
else {
n = fread(buffer, 1, 1000, sourceFile); /* grab all the text */
fwrite(buffer, 1, n, destinationFile); /* put it in file2.c */
fclose(sourceFile);
fclose(destinationFile);
destinationFile = fopen("file2.c", "r");
n = fread(buffer, 1, 1000, destinationFile); /* read file2.c */
printf("%s", buffer); /* display it all */
fclose(destinationFile);
return 0;
}
}
Reference link:
http://irc.essex.ac.uk/www.iota-six.co.uk/c/i4_fwrite_fscanf_fprintf.asp