Create file in C
Create a text file in C and enter some content in it and close the file.
Code
/****Write a program to create a file****/
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp; //Taking a file pointer variable
char fname[30],ch;
//Taking a file name from the user with its extension
printf("\nEnter a file name: ");
gets(fname);
//Open the file in write mode
fp=fopen(fname,"w");
if(fp==NULL)
{
printf("\nFile cannot be created.");
exit(0);
}
//Write the content from the console to the file
printf("\nEnter contain of the file: \n");
while((ch=getchar())!=EOF)
{
putc(ch,fp);
}
printf("\nFile created successfully.");
//Close the file
fclose(fp);
return 0;
}
Output
Enter a file name: temp.txt Enter contain of the file: This is a temporary file. ^Z File created successfully.