C Language Open and write to file


Example

#include <stdio.h>   /* for perror(), fopen(), fputs() and fclose() */
#include <stdlib.h>  /* for the EXIT_* macros */
 
int main(int argc, char **argv)
{
    int e = EXIT_SUCCESS;

    /* Get path from argument to main else default to output.txt */
    char *path = (argc > 1) ? argv[1] : "output.txt";

    /* Open file for writing and obtain file pointer */
    FILE *file = fopen(path, "w");
    
    /* Print error message and exit if fopen() failed */
    if (!file) 
    {
        perror(path);
        return EXIT_FAILURE;
    }

    /* Writes text to file. Unlike puts(), fputs() does not add a new-line. */
    if (fputs("Output in file.\n", file) == EOF)
    {
        perror(path);
        e = EXIT_FAILURE;
    }

    /* Close file */
    if (fclose(file)) 
    {
        perror(path);
        return EXIT_FAILURE;
    }
    return e;
}

This program opens the file with name given in the argument to main, defaulting to output.txt if no argument is given. If a file with the same name already exists, its contents are discarded and the file is treated as a new empty file. If the files does not already exist the fopen() call creates it.

If the fopen() call fails for some reason, it returns a NULL value and sets the global errno variable value. This means that the program can test the returned value after the fopen() call and use perror() if fopen() fails.

If the fopen() call succeeds, it returns a valid FILE pointer. This pointer can then be used to reference this file until fclose() is called on it.

The fputs() function writes the given text to the opened file, replacing any previous contents of the file. Similarly to fopen(), the fputs() function also sets the errno value if it fails, though in this case the function returns EOF to indicate the fail (it otherwise returns a non-negative value).

The fclose() function flushes any buffers, closes the file and frees the memory pointed to by FILE *. The return value indicates completion just as fputs() does (though it returns '0' if successful), again also setting the errno value in the case of a fail.