Create a Text File & Write Text — C File Handling Solution
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program to Create a New Text File and Write Text in It

In this tutorial, you'll learn how to create a new text file and write text into it using the C programming language. This is the very first step in file handling: before you can read, append, search, or copy a file, you need to know how to create one and put data into it. The program uses three core functions — fopen(), fprintf(), and fclose() — and includes proper error handling so you can tell the difference between "the file was created" and "something went wrong."

C program to create a new text file and write text in it using fopen, fprintf, and fclose with step-by-step explanation.

📝 Problem Statement

Write a program in C language to create a new text file and write some text in it.

⚙️ How the Program Works

The program follows the standard file-handling lifecycle in C:

  1. Declare a file pointer of type FILE *.
  2. Open the file using fopen("filename.txt", "w"). The "w" mode creates the file if it does not exist, or truncates it to zero length if it already exists.
  3. Check for errors — if fopen returns NULL, the file could not be opened (e.g., permission denied), and the program should report that and exit.
  4. Write text using fprintf(), which works like printf() but sends output to a file instead of the screen.
  5. Close the file with fclose() to flush buffered data to disk and release the file handle.

💻 Complete C Program

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    /* File pointer to hold the file handle */
    FILE *fp;

    /* Open the file in write mode.
       "w" creates the file if it does not exist,
       or truncates it if it already exists. */
    fp = fopen("sample.txt", "w");

    /* Check whether the file was opened successfully */
    if (fp == NULL)
    {
        printf("Error: Could not create the file.\n");
        return 1;
    }

    /* Write text to the file */
    fprintf(fp, "Hello, World!\n");
    fprintf(fp, "This text was written using fprintf.\n");
    fprintf(fp, "File handling in C is fun!\n");

    /* Close the file to flush data and release resources */
    fclose(fp);

    printf("File created and text written successfully.\n");

    return 0;
}

🖥️ Sample Output

Console output: File created and text written successfully.
Contents of sample.txt: Hello, World!
This text was written using fprintf.
File handling in C is fun!

🔍 Line-by-Line Explanation

Line / Code Explanation
#include <stdio.h> Provides declarations for fopen, fprintf, fclose, and printf.
#include <stdlib.h> Included for NULL and general utility functions (optional here, but good practice).
FILE *fp; Declares a file pointer. FILE is an opaque structure defined in stdio.h; you never manipulate its fields directly.
fopen("sample.txt", "w") Opens (or creates) the file named sample.txt in write mode. If the file exists, its contents are erased.
if (fp == NULL) Checks for failure. fopen returns NULL if the file could not be opened.
fprintf(fp, "...") Writes formatted text to the file. Works like printf but with the file pointer as the first argument.
fclose(fp); Flushes any buffered data to disk and releases the file handle. Always call this when you're done.

📂 Understanding File Modes

The second argument to fopen decides what you can do with the file. Here are the most common modes:

Mode Meaning Creates file? Truncates existing file?
"r" Read only No No
"w" Write only Yes Yes
"a" Append Yes No (writes at end)
"r+" Read and write No No
"w+" Read and write Yes Yes
"a+" Read and append Yes No (writes at end)
⚠️ Important: Using "w" on an existing file erases its contents. If you want to add to a file without losing its data, use "a" (append mode) instead — that's covered in Assignment 14.

🔁 Common Variations

Once you understand the basic pattern, you can adapt it in a few useful ways:

  • Let the user choose the filename: read a string into a character array with fgets, strip the trailing newline, then pass it to fopen.
  • Write more than one line: call fprintf multiple times, or loop over a string array.
  • Write a single character at a time: use fputc(c, fp) instead of fprintf.
  • Write raw bytes: use fwrite in binary mode ("wb") — that's the topic of Assignment 7.

💡 Tips & Best Practices

  • Always check fopen for NULL before writing — an unchecked file pointer will crash the program.
  • Always call fclose. Without it, buffered data may never reach the disk, and the OS may eventually refuse to open new files.
  • Compile with gcc -Wall -Wextra -std=c11 -g to catch mistakes like unused file handles.
  • On Windows, if you open a file with a path, use double backslashes ("C:\\temp\\sample.txt") or forward slashes ("C:/temp/sample.txt").

📖 Related Tutorials in This Series

  • File Handling Assignments — Complete Index
  • 4. Read and Display the Contents of a Text File
  • 14. Append Text to an Existing Text File
  • 5. Count Characters, Words, and Lines in a Text File
  • File Handling in C — Introduction
  • Operations Done in File Handling
  • Files FAQ

Back to Index: -->> File Handling Assignments in C   ||   Next Problem: -->> 2. Search for a Specific Word in a Text File


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processiong
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.