Introduction to File Operations in C Programming language
As we all know, the operations we perform via. printf and scanf, reads and stores data in the memory. But this memory is limited for use. If in case we need to read and store large amount of data then this limited memory can’t be used. We need to find some ways to store this data permanently so that we can read and write to it at later point of time. This is where file operations comes into picture. C provides us with the facility to perform File operations in C programming language.
File Operations in C Programming Language:
There are different operations that can be carried out on a file. These are:
- Creation of a new file
- Opening an existing file
- Reading from a file
- Writing to a file
- Moving to a specific location in a file (seeking)
- Closing a file
Below is the program to read a file and displays its contents on the screen.
/*Display contents of a file on screen*/ #include<stdio.h> void main() { FILE *fp; char ch; fp = fopen("file1.C","r"); while(1) { ch = fgetc(fp); if (ch == EOF) break; printf("%c", ch); } fclose(fp); }
On execution of this program it displays the contents of the file “file1.C” on the screen. We will understand this in the later sections.
Didn’t understand how the condition works in while(1)
In boolean, 1 means true and 0 means false.
Here, while(1) is read as while(true) which means the condition in the while loop is set to true and hence while loop will be executed idefinitely.
We have a condition inside a while loop,
if (ch == EOF)
break;
Which means, if we received End Of File, then break the indefinite while loop and exit.
Hope its clear.
Thanks,
Learn C Online Team
Now learn C++ online – visit http://www.learncpponline.com
Awesome… it’s clear, by the way, excellent site, please continue!
Thank you very much
plz clear me that concept