Getting Started with the C Fopen Method
File Handling is an essential part of every programming language. In almost every application, files are used to save data or information which can be an input, output, a database table information or important data that is required to complete the process of application. Therefore, learning file handling is extremely important. In files, data is saved as a sequence of bytes. The process of reading contents of a file in a software application and writing to a file is called ‘File I/O’ (File Input and Output). The C programming languages provides many standard library functions for File I/O in one C standard library header called ‘stdio.h’. Some of the important File I/O functions are ‘fopen’, ‘fclose’, ‘fread’, ‘fwrite’, ‘fgets’, ‘fputs’, ‘fscanf’ and ‘fprintf’. To start any File I/O operation, the first method that is used to open file for read and write is C ‘fopen’ method.
Want to learn more about C language? Learn more at Udemy.com.
What is C fopen Method?
The C ‘fopen’ method is a high level wrapper for the system call ‘open’ in the Unix OS. It is used to create a file or perform File I/O operations on existing file based on the mode specified.
C fopen Method Format
FILE *fopen (const char *filename, const char *openmode);
In the above format, the argument ‘filename’ is a pointer to a character string that has a name of file to be opened. The ‘openmode’ argument is a pointer to a character string that specifies the type of access (mode) requested by a program. This mode provides a way to restrict use of file by an application. C ‘fopen’ return a FILE pointer that is used by the program to keep track of opened file.
Different Modes in C ‘fopen’ Method
The following list is the ‘fopen’ access modes:
- Mode ‘r’ opens a file for reading when the file already exists, otherwise produce an error of open file failure.
- Mode ‘w’ creates a new file for writing and destroys the content of file when if already exist.
- Mode ‘a’ creates a new file for writing and writes data at the end of the file without truncating the existing file data.
- Mode ‘r+’ and ‘w+’ are the extended versions of ‘r’ and ‘w’ respectively with addition of read/write access.
- Mode ‘a+’ is the extended version of ‘a’ and creates a new file for read/write access. Reading starts from the beginning of the file and writing is done at the end of the existing data.
Some additional characters can be optionally specified with the above modes to achieve different types of access; for instance ‘b’ opens a text file in binary mode (random access) but this feature is available in only Windows-based OS. The character ‘x’ can be specifies with mode ‘w’ to avoid data truncation if file already exist.
The ‘+’ in ‘fopen’ access mode requests a stream that can perform both read and write. Therefore, this type of stream requires file positioning function like ‘fseek’ when switching from read to write or vice versa. Otherwise, read and write data can be intermingled with each other in any order because of the internal buffers that are not properly emptied during switching between read/write. But when a file is opened with append mode, then the write operation can only be perform in the end of the file even the file pointer points the middle of file (American National Standards Institute (ANSI) standard for C ‘fopen’).
For more C tutorials, take a course at Udemy.com.
How C fopen Method Works?
Before implementing C ‘fopen,’ the following are the important points that must be kept in mind to avoid an error when you call the method:
- When a named file in ‘fopen’ has an access mode of ‘w’ or ‘a’, then a file and its parent directory should have proper permissions like a writing permission should have assigned to it.
- New ‘fopen’ call should not exceed the total number of files allow to open in a program.
- Named file should not have size more than 2GB (‘fopen’ limit).
- As C ‘fopen’ supports large file thus make sure sufficient storage space is available.
FILE *file;
int characterValue;
file = fopen (“TestFile.txt”, “r”);
if (file == NULL) {
printf(“Error”);
}
else {
characterValue = fgetc( file );
while (characterValue != EOF) {
printf(“%c”, characterValue);
characterValue = fgetc( file );
}
}
fclose(file);
In the above code snippet, the C ‘fopen’ method opens a file named ‘TestFile.txt’ with mode of ‘r’, means read only. When a file exists, ‘fopen’ returns FILE pointer on success, otherwise a ‘NULL’ is return and ‘Error’ is printed on the console. When method has a success with opening a file, ‘else’ executes and it prints out all the characters of a file on the console until a seek pointer reaches the end of file (EOF). In the above code ‘fgetc’ method returns a single character of a file and seeks a read pointer to the next character. An ‘EOF’ is a constant with a value of ‘-1’ which shows the end of file while reading. Finally, the ‘fclose’ method releases a resource (FILE pointer) held by a program during execution.
C fopen Variant ‘fopen64’
FILE *fopen64 (const char *filename, const char *openmode);
C ‘fopen64’ is a 64 bit variant of ‘fopen’ which helps open a file larger than 2GB (fopen limit) on 32 bit machines. Alternative to this method is ‘fopen’ but the sources are compiled with _FILE_OFFSET_BITS == 64 flag.
C fopen Modified Variant ‘freopen’
FILE * freopen (const char *filename, const char * openmode, FILE *stream)
Unlike C ‘fopen’, ‘freopen’ has a third argument of type FILE stream that is already open in a program. It closes the open stream, reopens it and associates it with file. This is similar to combination of ‘fclose’ and ‘fopen’. The ‘freopen64’ is a 64 bit variant of ‘freopen’ same as ‘fopen64’ of ‘fopen’. The ‘freopen’ method is mostly used when an open stream of standard input (stdin), output (stdout) and error (stderr) has to be attached with a file. Following code snippet demonstrates the creation of log file for output (stdout).
FILE *fileHandler;
fileHandler = freopen(“output.txt”, “w+”, stdout);
fprintf(stdout,”This text is redirected to output.txt\n”);
fclose(fileHandler);
To learn the essentials of the C language, check out this course.
Recommended Articles
Top courses in C# (programming language)
C# (programming language) students also learn
Empower your team. Lead the industry.
Get a subscription to a library of online courses and digital learning tools for your organization with Udemy Business.