File Input/Output

 Why we need file input/output programming?

As we know it is not enough to just display the data on screen because if data is large  ,only a limited amount of data can be stored in memory and limited amount of it can be displayed on screen ,that’s why we need to store in a file or in a disk so that we can retrieve it later in some parts or whole data.

As we know memory is volatile so as soon as program is terminated we lost our whole data ,so it’s inappropriate to store the data in memory. Now of need the same data again either we have to retype it or regenerate it programmatically.

Obviously both the ways are tedious so we find a new way to store in a file or in a disk so that we can retrieve the whole data .

Now start by writing code……

Before you start==>

before you start file I/O you must learn how to compile c Program .

To learn compiling with visual studio(for windows) click here and to learn compiling with gcc(for windows and linux both) click here .

Code:To display contents of file

#include<stdio.h>
 int main( )
{
FILE *f;
char ch;
f=fopen(“buffercode.txt”,”r”);
while(1)
{
ch=fgetc(f);
if(ch==EOF)
break ;

                      print(%ch”,ch);
}
printf(“nProgramming by Buffercode”);
fclose( f);
return 0;
}

 How it works??

1) Make a file pointer which points to the address of file.

2)Now open the file by using  fopen( “filename”,”mode”)  in read mode and assign it’s address in file pointer.

3)To read the file’s content from memory use function fgetc()  and buffer it’s character in a char type variable under a while() loop.

4)if EOF (refers to ender of file) break the program.

5)print the character using printf() function.

6)Close the file by using fclose().

 Trouble in opening a file:

Sometimes when we try to open a file using fopen(), it may be possible that file will not be open. There are several reasons for this:

  • The file or disk may be write protected.
  • The space may insufficient .
  • The disk is damaged ,etc…

So before trying to read or write to the file , it is important for any program to access that file. If a program will fail to open the file due to any of the reasons ,the fopen() returns the NULL  value which is defined in “stdio.h”. Here is the simple program to handle this problem

#include<stdio.h>#include<stdlib.h>
int main()
  {
      FILE *fp;
      fp=fopen(“buffercode.txt”,”r”);
      if(fp==NULL)
      {
         puts(“Error in opening the file”);
         exit(1);
       }
       else
       {
        while(!)
           {
              ch=fgetc(f);
               if(ch==EOF)
               break ;                     
             
               print(%ch”,ch);
            }
            printf(“nProgramming by Buffercode”);
            fclose( f);
          }
       return 0;
  }.

You must see

Post your comment if you have any problem or you like it .

NO COMMENTS