Introduction of file handling
In this article, we are going to discuss File handling in C. If I want to store data inside a file then file handling is a concept. We can perform different operations on the file.
For example, we can create a new file, open a file, close a file, etc. We will understand how we can perform all these activities. There are specific functions for doing such activities.
All the functions are:
- fopen() : With the help of fopen(), you can open a new or existing file.
- fprintf(): We can write into a file
- fscanf(): We can read from the file
- fputc(): Write a character into the file as c represents a character
- fputw(): Write an integer into the file as w represents an integer
- fgetc(): Read a character from the file
- fgetw(): Read an integer from the file
- fclose: to close the file
- fseek(): to move to the specific location of the file
- rewind(): set our file pointer to the beginning
- ftell(): Will return the current position
Reading from the file code
#include<stdio.h>
#include<stdlib.h>
int main()
{
FILE *fptr=fopen("path","r");
char ch;
ch=getc(fptr);
while(ch!=EOF)
{
printf("%c",ch);
ch=getc(fptr);
}
fclose(fptr);
return 0;
}
Explanation of the above code
For example,
*fptr is a pointer that points to the file. We are trying to read the content from the while. The file content is in character so we are using getc() to read the characters.
The first line opens the file by considering the path. r denoted to read so the content will be read.
Next, the loop will read the character till we find the end of file. After we reach the end of the file, we stop reading the characters and we get the content of the file.
Finally, we use fclose() to close the file as we did the task which is reading from the file.
Writing to the file in file handling
#include<stdio.h>
#include<stdlib.h>
int main()
{
FILE *fptr=fopen("path","w");
fprintf(fptr, "contents to be written");
fclose(fptr);
puts("Values have been added to the file");
return 0;
}
As we need to write the data in the file, we have fprintf() where we can write what we want to display in the file. Then we can close the file with the help of fclose().
This is how we can write to the file.
Conclusion of file handling
File handling provides a mechanism to store the output of a program in a file and perform various operations on it.
Reference
http://www.freebookcentre.net/Language/Free-C-Books-Download.html
Also, read
https://curledmark.in/the-largest-number-program-in-an-array-in-c-programming/
https://curledmark.in/armstrong-number-and-arrays-in-c-programming/
https://curledmark.in/prime-reversepower-programs-in-c-programming/
The Book Of Five Rings Summary
How to Talk to Anyone by Leil Lowndes
Jonathan Livingston Seagull Book Summary
More Stories
What is do-while loop in C Programming ? Loops
What are loops in C programming?For,While,Do-While
What are Functions in C Programming