Create A New Text File


Explanation

In C, a file can be created using the fopen() function. The file is opened in "wt" (write text) mode, which creates a new text file. If the file already exists, its previous contents are erased. The fprintf() function is then used to write text into the file.

How It Works?

  • Step 1: Include the stdio.h header file for file handling functions.
  • Step 2: Declare a file pointer using FILE *fp.
  • Step 3: Open the file using fopen("any.txt", "wt").
  • Step 4: Write text into the file using the fprintf() function.
  • Step 5: Close the file using fclose() after writing the data.
  • Step 6: Run the program and check the created any.txt file.

Example Program


#include <stdio.h>

main()
{

    FILE *fp;

    clrscr();

    fp = fopen("any.txt", "wt");

    fprintf(fp, "hello india");

    fprintf(fp, "\n form of Program");

    fclose(fp);

    getch();

}

Output

The file any.txt will be created with the following contents:

hello india
form of Program

Practice Exercises

Task 1: Write a C program to create a text file named student.txt and write the following information into it:
  • Name: Rahul
  • Course: BCS
  • City: Pune
Goal: Learn how to create a text file using fopen() and write data into it using fprintf().

💡 Hint: Open the file in "wt" mode, use multiple fprintf() statements to write the data, and close the file using fclose().
💡 Show Solution

#include <stdio.h>
#include <conio.h>

main()
{

    FILE *fp;

    clrscr();

    fp = fopen("student.txt", "wt");

    fprintf(fp, "Name : Rahul");

    fprintf(fp, "\nCourse : BCS");

    fprintf(fp, "\nCity : Pune");

    fclose(fp);

    getch();

}

Output

The file student.txt will contain:

Name : Rahul
Course : BCS
City : Pune
Explanation: The program creates a new text file named student.txt using fopen() in write mode ("wt"). The fprintf() function writes the student's details into the file line by line. Finally, fclose() closes the file and saves the data successfully.