×

C Programs

C Basic & Conditional Programs

C Looping Programs

C String Programs

C Miscellaneous Programs

C program to create a text file using file handling, example of fopen, fclose

By IncludeHelp Last updated : March 10, 2024

Creating a text file in C

To create a text file in C, use the fopen() function by passing the file name to be created and file mode. File mode defines the mode of writing or reading a file.

Syntax

Below is the syntax of creating a file in C:

file_pointer = fopen("file_name","mode");

C program to create a text file

Below is a C program to create a text file using file handling. This is an example of fopen() and fclose() methods. Which are used for opening and closing a file respectively.

#include< stdio.h >
int main()
{
 
    FILE *fp;   /* file pointer*/
    char fName[20];
 
    printf("Enter file name to create :");
    scanf("%s",fName);
 
    /*creating (open) a file, in “w”: write mode*/
    fp=fopen(fName,"w");
    /*check file created or not*/
    if(fp==NULL)
    {
        printf("File does not created!!!");
        exit(0); /*exit from program*/
    }
 
    printf("File created successfully.");
    return 0;
}

Output

Run 1:
Enter file name to create : file1.txt
File created successfully.

Run 2:
Enter file name to create : d:/file1.txt
File created successfully.

“file will be created in d: drive”.

Run 3:
Run 1:
Enter file name to create : h:/file1.txt
File does not created!!!

C File Handling Programs »

Related Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.