Program to create file in C
Implementation
Now, we shall see the actual implementation of the program −
#include <stdio.h>
#include <sys/stat.h>
int main()
{
FILE *fp;
struct stat st;
char *filename = "sample.txt";
int flag;
flag = stat(filename, &st);
if(!flag)
{
printf("File already exists. \n");
return 0;
}
else
printf("File does not exist. \n");
/* open for writing */
fp = fopen(filename, "w");
if( fp == NULL )
{
printf("%s can not be opened. \n", filename);
return -1;
}
else
{
printf("File: %s created.\n", filename);
}
if( !fclose(fp) )
printf("File: %s closed.\n", filename);
flag = stat(filename, &st);
if(!flag)
{
printf("File exists.\n");
return 0;
}
else
printf("File does not exist.\n");
return 0;
}
Output
Output of this program should be −
File does not exist. File: sample.txt created. File: sample.txt closed. File exists.
Advertisements