Skip to main content

Hello World with Files

Files are used to hold information that we want to save for future use. The programs that we have been writing have been saved onto files. When the compiler turns our C programs into executables, those executables are stored into another file. However, other than programs and source code, the data that our programs produce can be sent to files.

To start with, let us consider the very first C program we wrote.. Hello World.

How would we rewrite this program so that instead of printing "Hello World!" to the screen, we printed it into a file called "hello.txt"?

File Handles

In order to do things with a file, we need to have a way to refer to a file from inside our program. We can do this by declaring a variable of type FILE* and using the fopen() function to associate a file with the variable.

The basic syntax is this:

FILE* variableName = fopen(filename, mode);

filename is a null terminated string with the name of the file.

mode is another string that indicates how we would use the file. For this example we will consider these two modes

"w" - write mode
"a" - append mode

For our problem we want to write "Hello World!" into a file named "hello.txt".

To do this, we would create a file pointer in "write" mode that is associated with this file.

Once we have this, we can use the function fprintf() to send our output to that file. fprintf() works pretty much like printf() except that it takes a file pointer as its first argument.

Once we are done with files, we want to ensure that our files are properly written and stored. We do this by closing the file using fclose() function.

//File related functions are part of stdio library
#include <stdio.h>

int main(void)
{
//fp is the name of a variable that is associated with a file
//we want to write our output to a file named hello.txt so
//we open that file in write mode by calling fopen() function
//fopen() is part of the stdio library
FILE* fp = fopen("hello.txt", "w");

//this next statement prints "Hello World".
//fp is a file pointer that we associated with "hello.txt"
//This next statement sends the string to the whatever file
//fp is is associated with.
//the "Hello World!\n" part is what we would normal give to
//printf(). it is the thing we want to output
fprintf(fp, "Hello World!\n");

//close the file using fclose(). Ensures files are correctedly
//cleaned up and saved
fclose(fp);

return 0;
}

If we compile the above program and run it, the string "Hello World!" will be written into the file hello.txt.

If we run it multiple times, hello.txt will have only one line that says "Hello World!". This is because write mode overwrites the existing file. If you were to edit the file and then run the program, the file's old content would be erased.

Append mode

Suppose we were to make this change to the code:

	FILE* fp = fopen("hello.txt", "a");

In otherwords.. everything else is the same but we open the file in append mode. If we did this, and run the program, each time the program runs, it would append "Hello World!" to the end of the file. This mode may be useful if you want to add information to the end of an existing file.

Checking for Successful File Opening

When we open a file using fopen(), there is a possibility of errors. For example, if we try to create a file in a folder where we do not have write permission, we would encounter an error. It is really important that we test whether we were successful in the opening of our file. If fopen() fails to open a file, the function returns NULL. NULL in C is typically the value we set for pointers that do not point to anything. It is falsey in nature. Thus testing:

if (fp != NULL) is the same as testing if(fp)

Before we write to a file, we should ensure that we were able to successfuly open the file for writing (or appending)

//File related functions are part of stdio library
#include <stdio.h>

int main(void)
{
FILE* fp = fopen("hello.txt", "w");

//test if file was correctly open
if(fp != NULL){
fprintf(fp, "Hello World!\n");

}
fclose(fp);

return 0;
}

input/output to a file can be done in a similar way to what we did interactively... we use fprintf() for output ans fscanf() for input. Once you open a file, the input/output components are not all that different. In the next example we will look closer at how to do input with fscanf()