Writing a file a character at a time
#include <stdio.h>
#include <string.h>
int main()
{
char mystr[80]="asdfasdf";
int i = 0;
int lstr = 0;
int mychar = 0;
FILE *pfile = NULL;
char *filename = "C:\\myfile.txt";
pfile = fopen(filename, "w");
if(pfile == NULL)
{
printf("Error opening %s for writing. Program terminated.", filename);
}
lstr = strlen( mystr );
for(i = lstr-1 ; i >= 0 ; i--)
fputc(mystr[i], 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);
}
Related examples in the same category