
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Basics of File Handling in C Programming
File Handling is the storing of data in a file using a program. In C programming language, the programs store results, and other data of the program to a file using file handling in C. Also, we can extract/fetch data from a file to work with it in the program.
The operations that you can perform on a File in C are −
Creating a new file
Opening an existing file
Reading data from an existing file
Writing data to a file
Moving data to a specific location on the file
Closing the file
Creating or opening file using fopen()
The fopen() function is used to create a new file or open an existing file in C. The fopen function is defined in the stdio.h header file.
Now, lets see the syntax for creation of a new file or opening a file
file = fopen(“file_name”, “mode”)
This is a common syntax for both opening and creating a file in C.
Parameters
file_name − It is a string that specifies the name of the file that is to be opened or created using the fopen method. mode: It is a string (usually a single character ) that specifies the mode in which the file is to be opened. There are various modes available to open a file in C, we will learn about all of them later in this article.
When will a file be created?
The fopen function will create a new file when it will not find any file of the specified name in the specified location. Else, if the file is found it will be opened with the mode specified.
Let’s see can example which will make the concept clear, Suppose we are opening a file named hello.txt using the fopen function. The following will be the statement,
file = fopen(“hello.txt”, “w”)
This will search for a file named hello.txt in the current directory. If the file exists, it will open the file otherwise it will create a new file named “hello.txt” and open it with write mode (specified using “w”).
Now, let’s see all types of modes that are available for us to read or write a file in C, and see code snippets that will show sample runs of the code.
Mode = “r” − open for reading, this mode will open the file for reading purpose only, i.e. the contents can only be viewed, nothing else like edits can be done to it.
This mode cannot create a new file and open() returns NULL, if we try to create a new file using this mode.
Example
#include <stdio.h> int main(){ FILE * file; if (file = fopen("hello.txt", "r")){ printf("File opened successfully in read mode"); } else printf("The file is not present! cannot create a new file using r mode"); fclose(file); return 0; }
Output
File opened successfully in read mode
We have created a file named hello.txt in our current directory but if we try to access other file then we will get “The file is not present! cannot create a new file using r mode” as output.
Mode = “rb” − open for reading in binary mode, this mode will open the file for reading in binary mode only, i.e. the contents can only be viewed and nothing else like edits can be done to it.
This mode cannot create a new file and open() returns NULL, if we try to create a new file using this mode.
Example
#include <stdio.h> int main(){ FILE * file; if (file = fopen("program.txt", "rb")){ printf("File opened successfully in read mode"); } else printf("The file is not present! cannot create a new file using rb mode"); fclose(file); return 0; }
Output
The file is not present! cannot create a new file using rb mode
Mode = “w” − open for writing only, this mode will open the file if present in the current directory for writing only i.e. reading operation cannot be performed. If the file is not present in the current directory, the program will create a new file and open it for writing.
If we open a file that contains some text in it, the contents will be overwritten.
Example
#include <stdio.h> int main(){ FILE * file; if (file = fopen("helo.txt", "w")){ printf("File opened successfully in write mode or a new file is created"); } else printf("Error!"); fclose(file); return 0; }
Output
File opened successfully in write mode or a new file is created
You can see here, we have tried to open file “helo.txt” which is not present in the directory, still the function returned the success message because it has create a file named “helo.txt”.
Mode = “wb” − open for writing in binary mode, this mode will open the file if present in the current directory for writing in binary mode i.e. reading operation cannot be performed. If the file is not present in the current directory, the program will create a new file and open it for writing in binary mode.
If we open a file that contains some text in it, the contents will be overwritten.
Example
#include <stdio.h> int main(){ FILE * file; if (file = fopen("hello.txt", "wb")){ printf("File opened successfully in write in binary mode or a new file is created"); } else printf("Error!"); fclose(file); return 0; }
Output
File opened successfully in write in binary mode or a new file is created
Mode = “a” − open for append only, this mode will open the file if present in the current directory for writing only i.e. reading operation cannot be performed. If the file is not present in the current directory, the program will create a new file and open it for writing. If we open a file that contains some text in it, the contents will not be overwritten; instead the new text will be added after the existing text in the file.
Example
#include <stdio.h> int main(){ FILE * file; if (file = fopen("hello.txt", "a")){ printf("File opened successfully in append mode or a new file is created"); } else printf("Error!"); fclose(file); return 0; }
Output
File opened successfully in append mode or a new file is created
Mode = “ab” − open for append in binary, this mode will open the file if present in the current directory for writing in binary only i.e. reading operation cannot be performed. If the file is not present in the current directory, the program will create a new file and open it for writing in binary.
If we open a file that contains some text in it, the contents will not be overwritten; instead the new text will be added after the existing text in the file.
Example
#include <stdio.h> int main(){ FILE * file; if (file = fopen("hello.txt", "ab")){ printf("File opened successfully in append in binary mode or a new file is created"); } else printf("Error!"); fclose(file); return 0; }
Output
File opened successfully in append in binary mode or a new file is created
Mode = “r+” − open for reading and writing both, this mode will open the file for both reading and writing purposes i.e. both read and write operations can be performed to the file.
This mode cannot create a new file and open() returns NULL, if we try to create a new file using this mode.
If we open a file that contains some text in it and write something, the contents will be overwritten.
Example
#include <stdio.h> int main(){ FILE * file; if (file = fopen("hello.txt", "r+")){ printf("File opened successfully in read and write both"); } else printf("The file is not present! cannot create a new file using r+ mode"); fclose(file); return 0; }
Output
File opened successfully in read and write both
We have created a file named hello.txt in our current directory but if we try to access another file then we will get “The file is not present! cannot create a new file using r+ mode” as output.
Mode = “rb+” − open for reading in binary mode, this mode will open the file for reading in binary mode only, i.e. the contents can only be viewed and nothing else like edits can be done to it.
This mode cannot create a new file and open() returns NULL, if we try to create a new file using this mode.
If we open a file that contains some text in it and write something, the contents will be overwritten.
Example
#include <stdio.h> int main(){ FILE * file; if (file = fopen("program.txt", "rb+")){ printf("File opened successfully in read mode"); } else printf("The file is not present! cannot create a new file using rb+ mode"); fclose(file); return 0; }
Output
The file is not present! cannot create a new file using rb+ mode
Mode = “w” − open for writing and reading, this mode will open the file if present in the current directory for writing and reading operation both. If the file is not present in the current directory, the program will create a new file and open it for reading and writing.
If we open a file that contains some text in it, the contents will be overwritten.
Example
#include <stdio.h> int main(){ FILE * file; if (file = fopen("helo.txt", "w+")){ printf("File opened successfully in read-write mode or a new file is created"); } else printf("Error!"); fclose(file); return 0; }
Output
File opened successfully in read-write mode or a new file is created
You can see here, we have tried to open file “helo.txt” which is not present in the directory, still the function returned the success message because it has create a file named “helo.txt”.
Mode = “wb+” : open for writing and reading in binary mode, this mode will open the file if present in the current directory for writing and reading in
binary mode. If the file is not present in the current directory, the program will create a new file and open it for reading and writing in binary mode. If we open a file that contains some text in it, the contents will be overwritten.
Example
#include <stdio.h> int main(){ FILE * file; if (file = fopen("hello.txt", "wb+")){ printf("File opened successfully in read-write in binary mode or a new file is created"); } else printf("Error!"); fclose(file); return 0; }
Output
File opened successfully in read-write in binary mode or a new file is created
Mode = “a+” − open for read and append, this mode will open the file if present in the current directory for both reading and writing. If the file is not present in the current directory, the program will create a new file and open it for reading and writing.
If we open a file that contains some text in it, the contents will not be overwritten; instead the new text will be added after the existing text in the file.
Example
#include <stdio.h> int main(){ FILE * file; if (file = fopen("hello.txt", "a+")){ printf("File opened successfully in read-append mode or a new file is created"); } else printf("Error!"); fclose(file); return 0; }
Output
File opened successfully in read-append mode or a new file is created
Mode = “ab+” − open for read and append in binary, this mode will open the file if present in the current directory for both reading and writing in binary. If the file is not present in the current directory, the program will create a new file and open it for reading and writing in binary. If we open a file that contains some text in it, the contents will not be overwritten; instead the new text will be added after the existing text in the file.
Example
#include <stdio.h> int main(){ FILE * file; if (file = fopen("hello.txt", "ab+")){ printf("File opened successfully in read-append in binary mode or a new file is created"); } else printf("Error!”); fclose(file); return 0; }
Output
File opened successfully in read-append mode or a new file is created
Reading Data for from an existing file
We can read content of a file in c using the fscanf() and fgets() and fgetc() functions. All are used to read contents of a file. Let’s see the working of each of the function −
fscanf()
The fscanf() function is used to read character set i.e strings from the file. It returns the EOF, when all the content of the file are read by it.
Syntax
int fscanf(FILE *stream, const char *charPointer[])
Parameters
FILE *stream: the pointer to the opened file. const char *charPointer[]: string of character.
Example
#include <stdio.h> int main(){ FILE * file; char str[500]; if (file = fopen("hello.txt", "r")){ while(fscanf(file,"%s", str)!=EOF){ printf("%s", str); } } else printf("Error!”); fclose(file); return 0; }
Output
LearnprogrammingattutorialsPoint
fgets()
The fget() function in C is used to read string from the stream.
Syntax
char* fgets(char *string, int length, FILE *stream)
Parameter
char *string: It is a string which will store the data from the string. int length: It is an int which gives the length of string to be considered. FILE *stream: It is the pointer to the opened file.
Example
#include <stdio.h> int main(){ FILE * file; char str[500]; if (file = fopen("hello.txt", "r")){ printf("%s", fgets(str, 50, file)); } fclose(file); return 0; }
Output
Learn programming at tutorials Point
fgetc()
The fgetc() function in C is used to return a single character from the file. It gets a character from the file and returns EOF at the end of file.
Syntax
char* fgetc(FILE *stream)
Parameter
FILE *stream: It is the pointer to the opened file.
Example
#include <stdio.h> int main(){ FILE * file; char str; if (file = fopen("hello.txt", "r")){ while((str=fgetc(file))!=EOF) printf("%c",str); } fclose(file); return 0; }
Output
Learn programming at tutorials Point
Writing Data to a file in C
We can write data to a file in C using the fprintf(), fputs(), fputc() functions. All are used to write contents to a file.
Let’s see the working of each of the function −
fprintf()
The fprintf() function is used to write data to a file. It writes a set of characters in a file.
Syntax
int fprintf(FILE *stream, char *string[])
Parameters
FILE for *stream: It is the pointer to the opened file. char *string[]: It is the character array that we want to write in the file.
Example
#include <stdio.h> int main(){ FILE * file; if (file = fopen("hello.txt", "w")){ if(fprintf(file, "tutorials Point”) >= 0) printf("Write operation successful"); } fclose(file); return 0; }
Output
Write operation successful
fputf()
The fputf() function in C can be used to write to a file. It is used to write a line (character line) to the file.
Syntax
int fputs(const char *string, FILE *stream)
Parameters
Constant char *string[]: It is the character array that we want to write in the file. FILE for *stream: It is the pointer to the opened file.
Example
#include <stdio.h> int main(){ FILE * file; if (file = fopen("hello.txt", "w")){ if(fputs("tutorials Point", file) >= 0) printf("String written to the file successfully..."); } fclose(file); return 0; }
Output
String written to the file successfully…
fputc()
The fputc() function is used to write a single character to the file.
Syntax
int fputc(char character , FILE *stream)
Parameters
char character : It is the character that we want to write in the file. FILE for *stream: It is the pointer to the opened file.
Example
#include <stdio.h> int main(){ FILE * file; if (file = fopen("hello.txt", "w")){ fputc('T', file); } fclose(file); return 0; }
Output
‘T’ is written to the file.
fclose()
The fclose() function is used to close the open file. We should close the file after performing operations on it to save the operations that we have applied to it.
Syntax
fclose(FILE *stream)
Parameters
FILE for *stream: It is the pointer to the opened file.
Example
#include <stdio.h> int main(){ FILE * file; char string[300]; if (file = fopen("hello.txt", "a+")){ while(fscanf(file,"%s", string)!=EOF){ printf("%s", string); } fputs("Hello", file); } fclose(file); return 0; }
Output
LearnprogrammingatTutorialsPoint
File contains
Learn programming at Tutorials PointHello
- Related Articles
- Basics of File Handling in C
- Exception Handling Basics in C++
- Basics of C++ Programming Language?
- File Handling in C#
- tellp() in file handling with C++
- File Handling through C++ Classes
- Set position with seekg() in C++ language file handling
- The Ultimate Guide to Mastering Ping in C Programming: Basics, Commands, and Troubleshooting
- File Operations in Rust Programming
- File Handling in Java using FileReader and FileWriter
- Error Handling in C
- Signal Handling in C++
- Input/Output from external file in C/C++, Java and Python for Competitive Programming
- How to configure handling and formatting of log file in Selenium with python?
- MySQL Command-Line Options that Affect Option-File Handling
