C Programming language

adplus-dvertising
C - File Operation : Write a File
Previous Home Next

How to write a file in C

When a file is opened for writing, it will be created if it does not already exist and it will be reset if it does, resulting in the deletion of any data already there. Using the 'w' indicates that the file is assumed to be a text file.

/** program to create a file and write some data into the file*/
#include<stdio.h>
 void main()
{
FILE *p;
char ch;
if((p==fopen("myfile.txt","w"))==NULL)
	{
printf("this file does not exist\n");
exit()
}
else
{
	printf("enter the text")

while((ch==getchar())!=EOF)
  /*press control z in Dos to stop reading  character*/
	fputc(ch,p);
}
fclose(p);
}
Previous Home Next