0
#include <stdio.h>
#include <stdlib.h>
int main()
{
  FILE *fp;
  char ch;
  
  fp=fopen("exp.txt","w");

  while( (ch=getchar()) !=EOF)
  {
          
    putc(ch,fp);
     
  }
  
  fclose(fp);
  return 0;
}

I am using gcc compiler in linux mint
This code is not working only exp.txt is created which is empty.

4
Contributors
4
Replies
6
Views
6 Years
Discussion Span
Last Post by Gaiety
0

Since "ch" has no value you don't write anything in the file

using getchar() we are taking input from the keyboard from the user

till it reaches the eof


but problem is how to take eof from the keyboard

0
#include <stdio.h>
#include <stdlib.h>
int main()
{
  FILE *fp;
  char ch;
  
  fp=fopen("exp.txt","w");

  while( (ch=getchar()) !=EOF)
  {
          
    putc(ch,fp);
     
  }
  
  fclose(fp);
  return 0;
}

I am using gcc compiler in linux mint
This code is not working only exp.txt is created which is empty.

your program is correct , just press CTRL+D at the end of your input.

however need to check whether file open is success.
fp = fopen("exp.txt","w");
if ( fp ) {
do file operations
}

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.