Easy to create a file in C program.
To create a file in C programming language, you typically use file handling functions such as fopen()
, fprintf()
, fclose()
, etc. Here’s a simple example that creates a text file and writes some data into it:
Example: Writing to a File in C
c
#include <stdio.h> int main() { // File pointer FILE *filePointer; // Open a file in write mode filePointer = fopen("example.txt", "w"); // Check if the file was opened successfully if (filePointer == NULL) { printf("Error opening file!\n"); return 1; } // Writing data to the file fprintf(filePointer, "This is an example of writing to a file in C.\n"); fprintf(filePointer, "File handling in C is useful!\n"); // Close the file fclose(filePointer); printf("Data written to the file successfully.\n"); return 0; }
Key Functions:
fopen("filename", "mode")
: Opens a file in the specified mode. Modes include:"w"
: Write mode (creates a new file if it doesn’t exist or truncates the existing file)."r"
: Read mode (opens an existing file for reading)."a"
: Append mode (opens a file for appending data to the end).
fprintf()
: Writes formatted data to the file.fclose()
: Closes the file and ensures that the data is written.
Output:
This program will create a file named example.txt
and write two lines into it. If you open the file after running the program, you will see the following content:
c
This is an example of writing to a file in C. File handling in C is useful!
Popular post
-
Eclipse IDE – Create New Java Project.
Opening the New Java Project…
-
How to start the project in android studio
Android Studio Open the Android…
-
How to use ACOSH function in excel
The ACOSH function returns the…
-
Complete Header tags in html – easy to learn
H tags can be used…
-
Best features in Python programme – easy to learn
Python is the most widely…