Using fopen( ), getc( ), putc( ), and fclose( ) to read char from console and write back to a file - C File

C examples for File:File Operation

Description

Using fopen( ), getc( ), putc( ), and fclose( ) to read char from console and write back to a file

Demo Code

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
   FILE *fp;//from w  w w. jav a  2 s .  c om
   char ch;

   if (argc != 2) {
      printf("You forgot to enter the filename.\n");
      exit(1);
   }

   if ((fp = fopen(argv[1], "w")) == NULL) {
      printf("Cannot open file.\n");
      exit(1);
   }

   do {
      ch = getchar();
      putc(ch, fp);
   } while (ch != '$');

   fclose(fp);

   return 0;
}

Result


Related Tutorials