Opening a file establishes a connection between a file on a storage device and a stream that a program can use to access the file. Once opened, the file can be read, written to, or both, depending on the mode used to open it.
Opening a file with fopen()
The fopen() library function is used to open a file:
FILE *fopen(const char *filename, const char *mode);
The fopen() function returns a pointer to a FILE object, which contains the information required to manage the file stream. If the file cannot be opened, the function returns NULL.
The filename parameter specifies the name or path of the file to open. It can be supplied as a string literal enclosed in double quotation marks or as a pointer to a string variable.
The mode parameter specifies how the file will be accessed. A file can be opened in text or binary mode for reading, writing, or both.
Values of mode for the fopen() function are listed below.
| Sr.No. | Mode & Description |
|---|---|
| r | Opens an existing text file for reading. |
| w | Opens a text file for writing. If it does not exist, then a new file is created. Here your program will start writing content from the beginning of the file. |
| a | Opens a text file for writing in appending mode. If it does not exist, then a new file is created. Here your program will start appending content in the existing file content. |
| r+ | Opens a text file for both reading and writing. |
| w+ | Opens a text file for both reading and writing. It first truncates the file to zero length if it exists, otherwise creates a file if it does not exist. |
| a+ | Opens a text file for both reading and writing. It creates the file if it does not exist. The reading will start from the beginning but writing can only be appended. |
If a file cannot be opened, fopen() returns NULL. Possible causes include an invalid filename, a nonexistent file or directory, insufficient permissions, or an unavailable storage device.
Closing a File
To close a file, use the fclose( ) function. The prototype of this function is −
int fclose( FILE *fp );
The fp parameter is a pointer to the FILE object associated with the file being closed.
The fclose() function returns 0 if the file is closed successfully, or EOF if an error occurs while closing it.
When a file is closed, any buffered output is flushed, meaning that pending data is passed to the underlying file system. The resources associated with the stream are then released. Closing a file also ensures that the program no longer uses that stream.
Writing to a File.
Data can be written to a disk file in three ways:
- Unformatted output: Uses functions such as
fputc()andfputs()to write individual characters or strings to a file without applying format specifiers. See c-input-and-output - Formatted output: Uses functions such as
fprintf()to write formatted data to a file. - Direct binary output: Uses
fwrite()to write blocks of bytes to a file, commonly for binary data.
Formatted output using fprintf
Formatted file output is done with the library function fprintf() . The prototype of fprintf() is-
int fprintf ( FILE * stream, const char * format, ... );
The first parameter is a pointer to type FILE. To write data to a storage location, use the pointer returned with the fopen() call.
The second argument is the format string. The format string used by fprintf() follows the same format as printf(). In the function prototype, ellipses represent a variable number of additional arguments.
The ellipsis (…) indicates that fprintf() accepts a variable number of additional arguments. These arguments supply the values that correspond to the format specifiers in the format string.
#include <stdio.h>
int main(void)
{
FILE *fp = fopen("data.txt", "w");
if (fp == NULL)
{
printf("Error opening file.\n");
return 1;
}
int age = 25;
fprintf(fp, "Age: %d\n", age);
fclose(fp);
return 0;
}
Output stored in data.txt:
Age:25
In this example, fprintf() writes the text Age: followed by the value of age. The %d format specifier is replaced by the integer value 25. The file is then closed using fclose().
Direct output with fwrite
The fwrite() function is used to write blocks of data, consisting of sequences of bytes, to an output stream. The data can include arrays, structures, or other objects stored in memory.
The syntax of the fwrite() function is:
fwrite( ptr, int size, int n, FILE *fp );
The fwrite() function accepts four arguments.
ptr points to the block of memory which contains the data items to be written.
size specifies the number of bytes of each item to be written.
n is the number of items to be written.
FILE* is a pointer to the file where data items will be written in binary mode.
When the code below is compiled and executed, it creates a new file test.txt and writes two lines.
#include <stdio.h>
int main(void)
{
FILE *fp = fopen("data.bin", "wb");
if (fp == NULL)
{
printf("Error opening file.\n");
return 1;
}
int numbers[] = {10, 20, 30, 40, 50};
fwrite(numbers, sizeof(int), 5, fp);
fclose(fp);
return 0;
}
Explanation:
- numbers is an array containing five integers.
- sizeof(int) specifies the size in bytes of each integer.
- 5 specifies the number of integers to write.
- fp is the pointer to the output file, opened in binary write mode (“wb“).
The fwrite() function writes the five integers directly from memory to data.bin as binary data. The file will contain the binary representations of the integers, not the readable text 10, 20, 30, 40, 50.
Reading from a file
Reading data complements the file-writing process and can be performed in three ways:
- Unformatted input: Uses functions such as
fgetc()andfgets()to read individual characters or strings from a file. See c-input-and-output - Formatted input: Uses functions such as
fscanf()to read formatted data from a file. - Direct input: Uses the
fread()function to read blocks of data directly into memory.
Formatted fscanf file input
The fscanf() function reads formatted input from a file. The prototype of fscanf() is-
int fscanf(FILE *fp, const char *fmt, ...);
The parameter fp is a pointer to a FILE object, usually returned by a successful call to fopen(). The parameter fmt is a format string that specifies how the input should be interpreted, using format specifiers such as %d for integers, %f for floating-point values, and %s for strings.
The ellipsis (...) indicates that the function accepts a variable number of additional arguments. These arguments are pointers to variables where the values read from the file will be stored.
The function returns the number of input items successfully read and assigned. If an input failure occurs before the first conversion is completed, it returns EOF.
#include <stdio.h>
int main(void)
{
FILE *fp = fopen("data.txt", "r");
if (fp == NULL)
{
printf("Error opening file.\n");
return 1;
}
char name[20];
int age;
if (fscanf(fp, "%19s %d", name, &age) == 2)
{
printf("Name: %s\n", name);
printf("Age: %d\n", age);
}
fclose(fp);
return 0;
}
John 25
Output:
Name: John
Age: 25
In this example, fscanf() reads a name and an integer from the file. The %19s format specifier limits the name to 19 characters to leave room for the terminating null character, while %d reads the age as an integer. The function returns 2 when both values are successfully read and assigned.
Direct input with the fread()
The fread() function is used to read blocks of binary data from a file. It complements the fwrite() function, which writes blocks of data to a file.
fread( ptr, int size, int n, FILE *fp );
The fread() function accepts four arguments.
ptr is the address of the memory block where data is stored after reading.
size specifies the number of bytes of each item to be read.
n is the number of items read from the file where each item occupies the number of bytes specified in the second argument.
FILE* is the file from where the data is read in binary mode.
The fread() function returns the number of complete items successfully read. If this value is less than count, the requested input was incomplete, possibly because the end of the file was reached or a read error occurred. The functions feof() and ferror() can be used to determine which condition occurred.
The file position indicator advances by the number of bytes actually read.
#include <stdio.h>
int main(void)
{
FILE *fp = fopen("data.txt", "r");
if (fp == NULL)
return 1;
char text[100];
size_t n = fread(text, 1, sizeof(text) - 1, fp);
text[n] = '\0';
printf("%s", text);
fclose(fp);
return 0;
}
Contents of data.txt:
Hello, world!
Output:
Hello, world!
In this example, fread() reads up to 99 bytes from the file into the text array. It returns the number of bytes read, which is stored in n. A null character (‘\0’) is then added to terminate the string before it is displayed using printf().
Sequential Versus Random File Access
Every file stream maintains a file position indicator that identifies the position where the next read or write operation will take place.
When data is read from or written to a file sequentially, the file position indicator advances automatically as each operation is performed.
Random file access allows a program to move the file position indicator to a specific location, making it possible to read or write data without first processing all the preceding data.
ftell() and rewind()
Its prototype is:
The rewind() function moves the file position indicator to the beginning of a file.
void rewind(FILE *fp);
The parameter fp is a pointer to the file stream. After rewind() is called, the file position indicator is set to the beginning of the file. The function also clears the stream’s end-of-file indicator and error indicator.
The ftell() function determines the current position of the file position indicator.
Its prototype is:
long ftell(FILE *fp);
The parameter fp is a pointer to the file stream. On success, ftell() returns a long value representing the current file position. For a binary stream, this is measured in bytes from the beginning of the file, with the first byte at position zero. For a text stream, the returned value may be a position indicator that should be used with fseek() rather than interpreted as a simple byte count.
If an error occurs, ftell() returns -1L.
fseek()
The fseek() function moves the file position indicator to a specified location relative to a reference point.
Its prototype is:
int fseek(FILE *fp, long offset, int origin);
The parameters are:
- fp — a pointer to the file stream.
- offset — the displacement from the reference point.
- origin — the reference point from which the displacement is measured.
The origin parameter can take one of three symbolic constants, defined in stdio.h:
| Constant | Value | Description |
|---|---|---|
| SEEK_SET | 0 | Measures the offset from the beginning of the file. |
| SEEK_CUR | 1 | Measures the offset from the current file position. |
| SEEK_END | 2 | Measures the offset from the end of the file. |
For binary streams, the offset is measured in bytes. A positive offset moves forward, while a negative offset moves backward relative to the reference point, where the resulting position is valid.
The function returns 0 on success and a non-zero value if an error occurs.
Manual control over the file position indicator is known as random file access. This means that the programmer can read data from or write data to any position in a file without reading or writing all the preceding data.
Example of Random File Access
#include <stdlib.h>
#include <stdio.h>
char readdate[] = "abcdefghijklmnopqrstuvwxyz";
int main(void)
{
FILE *fp;
char buf[2];
if ((fp = fopen("random.TXT", "w")) == NULL)
{
fprintf(stderr, "Error opening file.\n");
return 1;
}
if (fputs(readdate, fp) == EOF)
{
fprintf(stderr, "Error writing to file.\n");
fclose(fp);
return 1;
}
fclose(fp);
if ((fp = fopen("random.TXT", "r")) == NULL)
{
fprintf(stderr, "Error opening file.\n");
return 1;
}
printf("File position after opening: %ld\n", ftell(fp));
if (fgets(buf, sizeof(buf), fp) != NULL)
{
printf("Character at position 0: %s\n", buf);
}
printf("Current file position: %ld\n", ftell(fp));
fseek(fp, 10, SEEK_SET);
printf("Moved file position to 10.\n");
if (fgets(buf, sizeof(buf), fp) != NULL)
{
printf("Character at position 10: %s\n", buf);
}
rewind(fp);
printf("File position after rewind: %ld\n", ftell(fp));
if (fgets(buf, sizeof(buf), fp) != NULL)
{
printf("Character at position 0: %s\n", buf);
}
fclose(fp);
return 0;
}
Output:
File position after opening: 0
Character at position 0: a
Current file position: 1
Moved file position to 10.
Character at position 10: k
File position after rewind: 0
Character at position 0: a
Explanation:
- The program writes the alphabet to random.TXT.
- It opens the file for reading. The file position indicator initially points to position 0.
fgets()reads the first character, a, and the position advances to 1.- fseek(fp, 10, SEEK_SET) moves the position indicator to position 10, where the character k is located.
rewind(fp)returns the position indicator to the beginning of the file, allowing the program to read a again.
Detecting the End of a File
There are two ways to detect end-of-file.
Detecting EOF character – When a character input function reads the EOF this indicates the end of the file
Checking FEOF character – The function feof() returns 0 if the end of file fp hasn’t been reached, or a nonzero value if end-of-file has been reached.
File Management Functions
Deleting a File
The remove() function is used to delete a file. Its prototype is:
int remove(const char *filename);
The parameter filename is a pointer to a string containing the name or path of the file to be deleted.
The function returns 0 if the operation succeeds or a non-zero value if an error occurs. Errors may occur if the file does not exist, the program lacks the necessary permissions, or the file cannot be removed for another reason.
Renaming a File
The rename() function changes the name or location of an existing file. Its prototype is:
int rename(const char *oldname, const char *newname);
The parameter oldname specifies the existing filename, while newname specifies the new filename or path.
The function returns 0 on success or a non-zero value if an error occurs.
The source file must exist, and the program must have the necessary permissions. If a file with the destination name already exists, the behaviour depends on the platform and whether the destination can be replaced. Renaming a file across different file systems may also fail.
Temporary File Names
A temporary file is used to store data temporarily while a program is running. It may be deleted when it is no longer needed or when the program terminates.
The tmpnam() function generates a string that represents a possible temporary filename. Its prototype is:
char *tmpnam(char *s);
If s is not NULL, it must point to a character array large enough to hold the generated filename. If s is NULL, the function may use an internal buffer.
The function returns a pointer to the generated filename, or NULL if it cannot generate one.
Important: tmpnam() is not recommended for secure applications because another process could create a file with the generated name before the program uses it. It also generates a filename rather than creating a temporary file. Prefer safer alternatives, such as tmpfile() for a temporary file that is automatically closed and removed when the stream is closed or the program terminates.
Example using tmpnam():
#include <stdio.h>
int main(void)
{
char temp[L_tmpnam];
if (tmpnam(temp) != NULL)
{
printf("Temporary name: %s\n", temp);
}
else
{
printf("Unable to generate temporary name.\n");
}
return 0;
}
This example generates and displays a possible temporary filename. It does not create a file.