Easy to create a file in C program.

blog img

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!

Share your thoughts

Your email address will not be published. All fields are required.

Related post

  1. Easy to read and write the JSON file

    In C, you can handle JSON data by using libraries…

  1. Easy to creating a Simple calculator in C.

    Here’s a simple calculator program in C that performs basic…

  1. Easy way to learn – Arithmetic operators in C

    Here’s a simple example of a C program that performs…

  1. Functions in C – how it’s work

    In C, functions are blocks of code that perform specific…

  1. How to learn constructor – in C

    In C, a constructor is not a built-in feature like…

Popular post

  1. Eclipse IDE – Create New Java Project.

    Opening the New Java Project…

  1. How to start the project in android studio

    Android Studio Open the Android…

  1. How to use ACOSH function in excel

    The ACOSH function returns the…

  1. Complete Header tags in html – easy to learn

    H tags can be used…

  1. Best features in Python programme – easy to learn

    Python is the most widely…