C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

File Handling in C

Create and write to a file

C Program: Create and Write to a File

C

#include <stdio.h>

 

int main() {

    FILE *fp;

    char data[200];

 

    // Step 1: Open file in write mode

    fp = fopen("output.txt", "w");

 

    // Step 2: Check if file opened successfully

    if (fp == NULL) {

        printf("Error! Could not create file.\n");

        return 1;

    }

 

    // Step 3: Get input from user

    printf("Enter text to write into the file:\n");

    fgets(data, sizeof(data), stdin);

 

    // Step 4: Write data to file

    fprintf(fp, "%s", data);

 

    // Step 5: Close file

    fclose(fp);

 

    printf("Data successfully written to 'output.txt'\n");

 

    return 0;

}

Output

 
Sample Output :
Enter text to write into the file:
Hello, this is a file write example in C.
Data successfully written to 'output.txt'

File content (output.txt) :
Hello, this is a file write example in C.