Sunday 21 January 2018

Closing A File & File Functions


Closing A File & File Functions


Closing A File & File Functions
When we have finished all operations the file must
be closed . This ensures that all outstanding information associated with the file is flushed out from the buffers and all links to the file are broken .It also prevents accidental misuse of data. The I/O library supports a  function to do this. It takes following form:

 fclose(file-pointer);



The getc() and putc() Functions:
The simplest fie I/O functions are getc() & putc().These are analogous to getchar and putchar() functions and handle one character at a time.Assume that a file that is opened with file pointer fp1. Then , the statement  putc(c,fp1); writes the character contained in the character
variable to the file associated with FILE pointer fp.Similerly , getc is used to read a character from a
file has been opened in read mode.

 For example , the statement    c=getc(fp2);
would read a character from the file whose pointer is fp2.
   The file pointer moves by one character position for every operation of getc or putc. The getc will return am end of file marker EOF , when end of file has been reached. Therefore the reading should be terminated when EOF is encountered.

// As a practical use of these character I/O functions we can copy the contents of one file into another. This program takes text file and copies then into another text file , character by character. //

#include"stdio.h"
main()
{
  FILE *fs,*fp;
  char ch;
  fs=fopen("pr1.c","r");
  if(fs==NULL)
  {
    puts("cannot open source file");
    exit();
  }
  ft=fopen("pr2.c","w");
  if(ft==NULL)
  {
    puts("cannot open target file");
    fclose(fs);
    exit();
  }
  while(1)
  {
   ch=fgetc(fs);
   if(ch==EOF)
   break;
   else
   fputc(ch,ft);
  }
  fclose(fs);
  fclose(ft);
}
The getw() and putw() Functions:
 The getw an putw functions are integer oriented functions.These are analogous to getc and putc functions and are  used to read and write integer values .These functions would be useful to deal with only integer data. The general forms of getw , putw are:

putw(integer,fp);
getw(fp);

The fgets() and fputs() functions:
For many purposes , character I/O is just what is needed . However , in some situations the usage of
functions which read or write entire strings might turn out to be more efficient.Reading or Writing strings of characters from and to files is as easy as reading and writing individual characters .

CATEGORY FUNCTIONS
High level , Text , Unformatted Character I/O Getc(),putc(),fgetc(),fputc(). Here getc() and putc() are macros where as fgetc() and fputc() are their function versions.
High level, Text , Unformatted String I/O Fgets(),fputs()
High level, Text , Unformatted int I/O No standerd I/O Library Functions
High level, Text , Unformatted float I/O No standerd I/O Library Functions

0 comments:

Post a Comment