Writing character to file

Writing character to file

Published by: Nuru

Published date: 21 Jun 2021

Writing character to file Photo

Writing character to file

For writing character to a file, the file must be opened in write mode.

Sytax: fp = fopen(filename,“w” );

  •  If the file does not exist already, it will be created.
  •  If the file does exist, it will be overwritten!
  •  So, be careful when opening files for writing, in case you destroy a file unintentionally!!!!
  •  Opening files for writing can also fail.
  • If you try to create a file in another user's directory where you do not have access you will not be allowed and fopen() will fail.
  •  Also if there is not sufficient memory to create files, it also fails.
  • So check whether file created or not after calling fopen().

 

Program:

#include
int main()
{
char ch;
FILE *fpw;
fpw = fopen("new.txt","w");

if(fpw == NULL)
{
printf("Error");
exit(1);
}

printf("Enter any character: ");
scanf("%c",&ch);

/* You can also use fputc(ch, fpw);*/
fprintf(fpw,"%c",ch);
fclose(fpw);

return 0;
}

This program asks the user to enter a character and writes that character at the end of the file. If the file doesn’t exist then this program will create a file with the specified name and writes the input character into the file.

Output:

writing character to file

writing character to file

writing character to file