File Handling
File Handling
1. Text files
• Text files are the normal .txt files. You can easily create text files using
any simple text editors such as Notepad.
• When you open those files, you'll see all the contents within the file as
plain text. You can easily edit or delete the contents.
• They take minimum effort to maintain, are easily readable, and
provide the least security and takes bigger storage space.
2. Binary files
• Binary files are mostly the .bin files in your computer.
• Instead of storing data in plain text, they store it in the binary form
(0's and 1's).
• They can hold a higher amount of data, are not readable easily, and
provides better security than text files.
working with files
• we need to declare a pointer of type file. This declaration is
needed for communication between the file and the program.
FILE *fptr;
• Open a file using the fopen() function defined in
the stdio.h header file.
• syntax for opening a file in standard I/O is:
ptr = fopen("fileopen","mode");
• For reading and writing to a text file, we use the
functions fprintf() and fscanf().
• They are just the file versions of printf() and scanf(). The only
difference is that fprintf() and fscanf() expects a pointer to the
structure FILE.
Reading File
• The fscanf() function is used to read set of
characters from file. It reads a word from the
file and returns EOF at the end of file.
• Syntax
• int fscanf(FILE *stream, const char *format [,
argument, ...])
Reading
#include <stdio.h>
main(){
FILE *fp;
char buff[255];//creating char array to store data of file
fp = fopen("file.txt", "r");
while(fscanf(fp, "%s", buff)!=EOF){
printf("%s ", buff );
}
fclose(fp);
}
Algorithm
1. Start
2. Declare variable and file pointer
3. Assign file pointer to fopen() function with
write format
4. Print an error message If the file is not opened
5. Else give the content using loop
6. Close the file
7. Stop
writing
include <stdio.h>
main(){
FILE *fp;
fp = fopen("file.txt", "w");//opening file
fprintf(fp, "Hello file by fprintf...\n");//
writing data into file
fclose(fp);//closing file
}
Writing File
• fprintf() function
• The fprintf() function is used to write set of
characters into file. It sends formatted output
to a stream.
• Syntax:
• int fprintf(FILE *stream, const char *format [,
argument, ...])
Reading File