Write to .txt file?
Categories:
Writing to Files in C on Linux: A Comprehensive Guide

Learn the fundamentals of creating, opening, writing to, and closing text files in C programming on a Linux system, covering various file I/O functions and error handling.
File I/O (Input/Output) is a fundamental aspect of programming, allowing applications to interact with the file system. In C, writing to a text file on a Linux system involves a series of steps: opening the file, writing data to it, and then closing it. This article will guide you through the essential functions and best practices for performing these operations reliably.
Understanding File Pointers and Modes
In C, files are accessed through a FILE
pointer, which is a structure defined in the <stdio.h>
header. This pointer acts as a handle to the file, allowing you to perform operations like reading and writing. When you open a file, you specify a 'mode' that dictates how the file will be accessed. Common modes for writing include:
"w"
: Write mode. Creates an empty file for writing. If a file with the same name already exists, its contents are truncated (deleted), and the file is treated as a new empty file."a"
: Append mode. Opens a file for writing at the end of the file. If the file does not exist, it is created."r+"
: Read/Write mode. Opens a file for both reading and writing. The file must exist."w+"
: Write/Read mode. Creates an empty file for both reading and writing. If a file with the same name already exists, its contents are truncated."a+"
: Append/Read mode. Opens a file for both reading and appending. If the file does not exist, it is created.
flowchart TD A[Start] --> B{Open File (fopen)}; B --"Mode: w, a, w+, a+"--> C{Check for NULL (Error)}; C --"NULL"--> D[Handle Error & Exit]; C --"Not NULL"--> E[Write Data (fprintf, fputs, fwrite)]; E --> F{Close File (fclose)}; F --> G[End];
Basic File Writing Process Flow in C
Opening, Writing, and Closing a File
The primary function for opening a file is fopen()
. It takes two arguments: the file path (as a string) and the mode (also as a string). It returns a FILE*
pointer on success, or NULL
if the file cannot be opened (e.g., due to incorrect permissions or an invalid path). After successfully opening a file, you can use functions like fprintf()
, fputs()
, or fwrite()
to write data. Finally, it's crucial to close the file using fclose()
to flush any buffered data and release the file handle, preventing data loss or resource leaks.
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *file_ptr;
const char *filename = "example.txt";
const char *content = "Hello, C file I/O!\nThis is a new line.\n";
// Open the file in write mode ("w")
// If example.txt exists, its content will be truncated.
// If it doesn't exist, it will be created.
file_ptr = fopen(filename, "w");
// Check if fopen was successful
if (file_ptr == NULL) {
perror("Error opening file"); // Prints a system error message
return EXIT_FAILURE; // Indicate an error
}
// Write content to the file using fprintf
fprintf(file_ptr, "%s", content);
fprintf(file_ptr, "Current year: %d\n", 2023);
// Close the file
if (fclose(file_ptr) == EOF) {
perror("Error closing file");
return EXIT_FAILURE;
}
printf("Successfully wrote to %s\n", filename);
return EXIT_SUCCESS; // Indicate success
}
Example of writing to a text file using fprintf()
in C.
fopen()
for NULL
to ensure the file was opened successfully. Using perror()
provides a helpful system error message.Appending to an Existing File
If you want to add content to the end of an existing file without overwriting its current contents, you should open the file in append mode ("a"
). If the file does not exist, fopen()
in append mode will create it, just like write mode.
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *file_ptr;
const char *filename = "example.txt";
const char *new_content = "Appending this line.\n";
// Open the file in append mode ("a")
// Content will be added to the end of the file.
file_ptr = fopen(filename, "a");
if (file_ptr == NULL) {
perror("Error opening file for appending");
return EXIT_FAILURE;
}
// Write new content to the file
fprintf(file_ptr, "%s", new_content);
// Close the file
if (fclose(file_ptr) == EOF) {
perror("Error closing file after appending");
return EXIT_FAILURE;
}
printf("Successfully appended to %s\n", filename);
return EXIT_SUCCESS;
}
Example of appending content to a text file using fprintf()
.
"w"
mode, as it will irrevocably delete the existing content of a file. If you intend to preserve data, use "a"
for appending or implement checks before overwriting.Writing Different Data Types
While fprintf()
is versatile for formatted output, you might also use fputs()
for writing strings or fwrite()
for writing blocks of binary data. For text files, fprintf()
and fputs()
are generally preferred.
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *file_ptr;
const char *filename = "data_types.txt";
char string_data[] = "This is a string written with fputs.\n";
int integer_data = 12345;
double double_data = 3.14159;
file_ptr = fopen(filename, "w");
if (file_ptr == NULL) {
perror("Error opening data_types.txt");
return EXIT_FAILURE;
}
// Using fputs to write a string
fputs(string_data, file_ptr);
// Using fprintf for formatted output
fprintf(file_ptr, "Integer value: %d\n", integer_data);
fprintf(file_ptr, "Double value: %.2f\n", double_data);
if (fclose(file_ptr) == EOF) {
perror("Error closing data_types.txt");
return EXIT_FAILURE;
}
printf("Successfully wrote various data types to %s\n", filename);
return EXIT_SUCCESS;
}
Demonstration of fputs()
and fprintf()
for different data types.
1. Compile the C program
Save your C code (e.g., write_file.c
) and compile it using GCC in your Linux terminal: gcc write_file.c -o write_file
2. Run the executable
Execute the compiled program: ./write_file
3. Verify the file content
Use the cat
command to view the content of the created or modified text file: cat example.txt
or cat data_types.txt