Monday, April 28, 2025

C Tutorial - 25 - How to Write to a File in C

#include <stdio.h>
#include <string.h>

int main()
{

    FILE *fp;

    char writeThisLine[100] = "This is some longer line to be writen to file";

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

    if (fp == NULL)
    {
        printf("Unable to open file for writing \n");
    }
    else
    {
        printf("File Opened \n");

        if (strlen(writeThisLine) > 0)
        {
            fputs(writeThisLine, fp);
        }

        fclose(fp);

        printf("Data successfully writen to file \n");
        printf("File closed \n");
    }

    return 0;
}

Result:

File Opened
Data successfully writen to file
File closed

Process returned 0 (0x0)   execution time : 0.047 s
Press any key to continue.

This program opens a file in write mode, writes a string to it using fputs(), and then closes the file using fclose(). Here's a line-by-line explanation:

#include <stdio.h>
#include <string.h>

These are the standard header files for input/output and string functions in C. 

int main()
{
    FILE *fp;

    char writeThisLine[100] = "This is some longer line to be written to file";

This declares a file pointer fp and a character array writeThisLine, which will store the string to be written to the file. 

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

This opens a file named "target_file.txt" in write mode, and sets the file pointer to point to the beginning of the file. 

    if (fp == NULL)
    {
        printf("Unable to open file for writing \n");
    }
    else
    {
        printf("File Opened \n");

        if (strlen(writeThisLine) > 0)
        {
            fputs(writeThisLine, fp);
        }

        fclose(fp);

        printf("Data successfully written to file \n");
        printf("File closed \n");
    }

    return 0;
}

This checks if the file was successfully opened. If it was, the program writes the string stored in writeThisLine to the file using fputs(), closes the file using fclose(), and prints messages indicating that the write was successful and the file was closed.

If the file couldn't be opened, the program prints a message indicating that the file couldn't be opened for writing.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...