write in a file in C by R4R Team

To write in file what things we require ?
-A file pointer.
-fopen() function to open file.
-fprintf() to write in file.
-fclose() to close the file.

Open file in write mode:
Syntax-
fp=fopen("Filename","w");

fprintf():
-This function are write the text content inside the file.
Syntax-
fprintf(fp,"Mydata");


program-

#include< stdio.h>
void main()
{
FILE *fp;
char data[50];
//open file in write mode
fp=fopen("myfile.txt","w");
printf("Enter Datan");
scanf("%s",&data);
printf("Now we put data inside the filen");
fprintf(fp,data);
fclose(fp);// close file
printf("Your file is safely closed now");
}


output-

Enter Data
This is my data which i store inside my file
Now we put data inside the file
Your file is safely closed now

-In this program, we take an input of the text and open the file in write mode then store input text inside the file as shown above.




Leave a Comment: