Save text content into a file
#include <stdio.h>
int main(){
char *proverbs[] ={"AAA\n","BBB\n","CCC\n"};
char more[60] = "DDD\n";
FILE *pfile = NULL;
int i = 0;
char *filename = "C:\\myfile.txt";
pfile = fopen(filename, "w");
if(pfile == NULL)
{
printf("Error opening %s for writing. Program terminated.", filename);
}
for(i = 0 ; i < sizeof proverbs/sizeof proverbs[0] ; i++)
fputs(proverbs[i], pfile);
fclose(pfile);
pfile = fopen(filename, "a"); /* Open it again to append data */
if(pfile == NULL)
{
printf("Error opening %s for writing. Program terminated.", filename);
}
fputs(more, pfile);
fclose(pfile);
pfile = fopen(filename, "r"); /* Open the file to read it */
if(pfile == NULL)
{
printf("Error opening %s for writing. Program terminated.", filename);
}
while(fgets(more, 60, pfile) != NULL)
printf("\n%s", more);
fclose(pfile);
remove(filename);
}
Related examples in the same category