This article is about file handling using C programming language. File stores information for many purposes and retrieve whenever required by our C programs. A file represents a sequence of bytes on the disk where a group of related data is stored. File is created for permanent storage of data. C programming language can handle files as Stream-oriented data (Text) files and System oriented data (Binary) files.

File handling in C++ works differently as discussed in C++ file handling tutorial. There is a separate article i.e. C++ tutorial for Java Programmers.

What is a File in C?

On an abstract level, a file is a collection of bytes stored on a storage device, which is generally a disk or other storage device. The collection of bytes may be interpreted, for example, as characters, words, lines, paragraphs and pages from a textual document; fields and records belonging to a database; or pixels from a graphical image. The meaning of the file is determined by the data structures and operations used by a program to process the file.

Essentially there are two kinds of files that programmers deal with i.e. text files and binary files as shown in the diagram above. These two classes of files will be discussed in the following sections.

1. What is ASCII Text file in C Programming?

A text file can be a stream of characters that a computer can process sequentially. It is not only processed sequentially but only in forward direction. A text file is usually opened for operations like reading, writing, or appending. Similarly, since text files only process characters, they can only read or write data one character at a time. In C Programming, functions are provided that deal with lines of text, but these still essentially process data one character at a time.

A text stream in C is a special kind of file. Depending on the requirements of the operating system, newline characters may be converted to or from carriage-return/linefeed combinations depending on whether data is being written to, or read from, the file. Other character conversions may also occur to satisfy the storage requirements of the operating system. These translations occur transparently and they occur because the programmer has signaled the intention to process a text file.

2. What is a Binary file in C Programming?

A binary file is no different to a text file but it is a collection of bytes rather than characters. In C Programming Language a byte and a character are equivalent. Hence a binary file is also referred to as a character stream, but there are two basic differences.

  1. No special processing of the data occurs and each byte of data is transferred to or from the disk unprocessed.
  2. C places no constructs on the file, and it may be read from, or written to, in any manner chosen by the programmer.

Binary files can be either processed sequentially or can be processed using random access techniques. In C, processing a file using random access techniques involves moving the current file position to an appropriate place in the file before reading or writing data. This indicates a second characteristic of binary files. They a generally processed using read and write operations simultaneously.

For example, a database file will be created and processed as a binary file. A record update operation will involve locating the appropriate record, reading the record into memory, modifying it in some way, and finally writing the record back to disk at its appropriate location in the file. These kinds of operations are common to many binary files, but are rarely found in applications that process text files.

How files are manipulated in C?

Now let’s see how files are created and processed in C programming language. In C,
function is used to get a pointer to file which can be used by compiler to perform input and output operations on files. The standard form or
function is:

A file can be opened in different modes depending upon the requirements. The
function uses the following modes to open the file.

  1. r – open for reading
  2. w – open for writing (file need not exist)
  3. a – open for appending (file need not exist)
  4. r+ – open for reading and writing, start at beginning
  5. w+ – open for reading and writing (overwrite file)
  6. a+ – open for reading and writing (append if file exists)

How to create a file in C?

In order to create files we have to learn about file I/O i.e. how to write data into a file and how to read data from a file. We will start this section with an example of writing data to a file. We begin as before with the include statement for stdio.h, then define some variables for use in the example including a rather strange looking new type.

The type FILE is used for a file variable and is defined in the stdio.h file. It is used to define a file pointer for use in file operations. Before we can write to a file, we must open it. What this really means is that we must tell the system that we want to write to a file and what the file name is. We do this with the
function illustrated in the first line of the program. The file pointer, fp in our case, points to the file and two arguments are required in the parentheses, the file name first, followed by the file type. The file name is any valid DOS file name, and can be expressed in upper or lower case letters, or even mixed if you so desire. It is enclosed in double quotes.

For this example we have chosen the name TENLINES.TXT. If you don’t have a file by this name, that is good because program will create one and put some data into it. You are permitted to include a directory with the file name.The directory must, of course, be a valid directory otherwise an error will occur. Also, because of the way C handles literal strings, the directory separation character must be written twice. For example, if the file is to be stored in the PROJECTS sub directory then the file name should be entered as “\\PROJECTS\\TENLINES.TXT”. The second parameter is the file attribute and can be any of three letters, r, w, or a, and must be lower case.

How to read a file using C program?

When an
is used as parameter to
, the file is opened for reading, a
is used to indicate a file to be used for writing, and an
indicates that you desire to append additional data to the data already in an existing file. Most C compilers have other file attributes available; check your Reference Manual for details. Using the
indicates that the file is assumed to be a text file. Opening a file for reading requires that the file already exist. If it does not exist, the file pointer will be set to NULL and can be checked by the program. Here is a small C program that reads a file and display its contents on screen.

How to writing to a file in C?

When a file is opened for writing, ‘w’ , it will be created if it does not already exist and it will be reset if it does, resulting in the deletion of any data already there. Using the w indicates that the file is assumed to be a text file. Here is the program to create a file and write some data into the file.

How to Append data to a file in C?

When a file is opened for appending, it will be created if it does not already exist and it will be initially empty. If it does exist, the data input point will be positioned at the end of the present data so that any new data will be added to any data that already exists in the file. Using the a indicates that the file is assumed to be a text file. Here is a program that will add text to a file which already exists and there is some text in the file.

The job of actually outputting to the file is nearly identical to the outputting we have already done to the standard output device. The only real differences are the new function names and the addition of the file pointer as one of the function arguments. In the example program, fprintf replaces our familiar printf function name, and the file pointer defined earlier is the first argument within the parentheses. The remainder of the statement looks like, and in fact is identical to, the printf statement.

Closing a file

To close a file you simply use the function
with the file pointer as the function parameter. Actually, in this simple program, it is not necessary to close the file because the system will close all open files before returning to DOS, but it is good programming practice for you to close all files in spite of the fact that they will be closed automatically, because that would act as a reminder to you of what files are open at the end of each program. You can open a file for writing, close it, and reopen it for reading, then close it, and open it again for appending, etc. Each time you open it, you could use the same file pointer, or you could use a different one. The file pointer is simply a tool that you use to point to a file and you decide what file it will point to. Compile and run this program. When you run it, you will not get any output to the monitor because it doesn’t generate any. After running it, look at your directory for a file named TENLINES.TXT and type it; that is where your output will be. Compare the output with that specified in the program; they should agree! Do not erase the file named TENLINES.TXT yet; we will use it in some of the other examples in this section.

How to read text from a file using C?

Now for our first program that reads text from a file. This program begins with the familiar include, some data definitions, and the file opening statement which should require no explanation except for the fact that an
is used here because we want to read it.

In this program we check to see that the file exists, and if it does, we execute the main body of the program. If it doesn’t, we print a message and quit. If the file does not exist, the system will set the pointer equal to NULL which we can test. The main body of the program is one do while loop in which a single character is read from the file and output to the monitor until an EOF (end of file) is detected from the input file. The file is then closed and the program is terminated. At this point, we have the potential for one of the most common and most perplexing problems of programming in C. The variable returned from the getc function is a character, so we can use a char variable for this purpose. There is a problem that could develop here if we happened to use an unsigned char however, because C usually returns a minus one for an EOF – which an unsigned char type variable is not capable of containing. An unsigned char type variable can only have the values of zero to 255, so it will return a 255 for a minus one in C. This is a very frustrating problem to try to find. The program can never find the EOF and will therefore never terminate the loop. This is easy to prevent: always have a char or int type variable for use in returning an EOF. There is another problem with this program but we will worry about it when we get to the next program and solve it with the one following that.

How to read and write Binary Files in C?

There are two main functions used to read and  write binary files in C Programming i.e.
. Both of these functions uses pointer to a memory location which can be array. Because they accept pointers, you can also use these functions with any other data structures as well. Standard declaration of
is as below:

Now let’s look a the following two programs to read and write binary files.

How to read contents of Binary File in C?

Related Article: File Handling in C++