Mega Code Archive

 
Categories / C / Code Snippets
 

Writing a file a character at a time

#include <stdio.h> #include <string.h> int main() { char mystr[80]="I Love Clementine"; int j = 0; int lstr = 0; int mychar = 0; FILE *pfile = NULL; char *filename = "C:\\testfile.txt"; pfile = fopen(filename, "w"); if(pfile == NULL) { printf("Error opening %s for writing. Program terminated.", filename); } lstr = strlen( mystr ); for(j = lstr-1 ; j >= 0 ; j--) fputc(mystr[j], pfile); /* Write string to file backwards */ fclose(pfile); /* Open the file for reading */ pfile = fopen(filename, "r"); if(pfile == NULL) { printf("Error opening %s for reading. Program terminated.", filename); } /* Read a character from the file and display it */ while((mychar = fgetc(pfile)) != EOF) putchar(mychar); putchar('\n'); fclose(pfile); remove(filename); }