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."
📝 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:
- Declare a file pointer of type
FILE *. - 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. - Check for errors — if
fopenreturnsNULL, the file could not be opened (e.g., permission denied), and the program should report that and exit. - Write text using
fprintf(), which works likeprintf()but sends output to a file instead of the screen. - 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
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) |
"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 tofopen. - Write more than one line: call
fprintfmultiple times, or loop over a string array. - Write a single character at a time: use
fputc(c, fp)instead offprintf. - Write raw bytes: use
fwritein binary mode ("wb") — that's the topic of Assignment 7.
💡 Tips & Best Practices
- Always check
fopenforNULLbefore 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 -gto 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").