Writing to a File

The fputc( ) function is similar to the putch( ) function, in the sense that both output characters. However, putch( ) function always writes to the VDU, whereas, fputc( ) writes to the file. Which file? The file signified by ft. The writing process continues till all characters from the source file have been written to the target file, following which the while loop terminates. The Following example demonstrates another good example of writing text files in C.

#include <stdio.h>
int main()
{
	FILE *fs, *ft;
	char *ch = "writing text files";
	int len;
	char in;
	int i;
	ft = fopen("targetfile.txt", "w");
	
	if (ft == NULL)
	{
		puts("Cannot open target file");
		fclose(fs);
		exit(0);
	}
	
	len = strlen(ch);
	for (i = 0; i < len; i++)
        {
        in = *(ch+i);
        fputc(in, ft);
        }

	fclose(ft);
	getchar();
	return 0;
}