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:

  1. Creation of a new file
  2. Opening an existing file
  3. Reading from a file
  4. Writing to a file
  5. Moving to a specific location in a file (seeking)
  6. 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.

You may also like...

4 Responses

  1. Anonymous says:

    Didn’t understand how the condition works in while(1)

  2. LearnCOnline says:

    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

  3. Anonymous says:

    Awesome… it’s clear, by the way, excellent site, please continue!
    Thank you very much

  4. Bhoopal Bisht says:

    plz clear me that concept

Leave a Reply

Your email address will not be published. Required fields are marked *

FREE C Cheatsheet - Speed Up Your C Programming.

FREE C Cheatsheet - Speed Up Your C Programming.

Download a 7-page free cheat sheet for easy and quick access to C Concepts, Snippets, and Syntax.

Thank you! Check you inbox and access your cheat-sheet