File Handling in C

C language permits the usage of limited input and output functions to read and write data. These functions are used for only smaller volumes of data and it becomes difficult to handle longer data volumes. Also the entire data is lost when the program is over.

 To overcome these difficulties a flexible method is developed by employing the concept of FILES to store, to read (0r) write data and to written them even when program is over.

Definition:-A FILE is one which enable the user to read , write and store agroup of a related data .  (or)  A FILE is a collection of related data stored in a particular area on the disk.

C supports a number of functions to have the ability to perform the basic file operations which indicates.

               1) Naming a file

               2) Opening a file

               3) Reading data from a file

               4) Writing data into file

               5) Closing a file

Text file or Sequential file:- For reading ad writing data in continuous blocks in this files the data is represented instead of characters.  Each and every character requires only one byte.

Binary files:- For reading and writing data in orbitary structured files. In this files the information is represented instead of data blocks the size of data blocks depends on its data type.

FILE: It is a predefined structure and is used to declare a file pointer. Using this pointer we can perform all file operations.

Declaration of file pointer:-                        FILE  *identifier;

Example:-        FILE *fp;

fopen():- It opens a file stream.

Syntax: FILE *fopen(const char *filename, const char *mode);

ARGUMENTS

file name:-  File that the functions open.

MODE DESCRIPTION:              

SnoModeDescription
1rOpen for reading only
2wCreate for writing (a file by that name already exists, it will be overwritten.)
3aend; open for writing at end of file, or create for writing if the file does not exist.
4r+Open an existing file for update (reading and writing)
5w+Create a new file for update (reading and writing). (If a file by that name already exists, it will be overwritten)
6a+Open for append; open for update at the end of the file, or create if the file does not exist.

*To specify that a given file is being opened or created in text mode, append “t” to the string (rt, w+t, etc.).

*To specify binary mode, append “b” to the string (wb, a+b, etc.).

fclose():- It closes a file stream.                   

Syntax:- int fclose(FILE *stream);

fcloseall() :- It closes all opened file streams.

Syntax:- int fcloseall(void);

TEXT FILES                                 

Macros:

1)getc():- It is a macro that gets one character from a stream.

Syntax: int getc(FILE *stream);

2)putc():- It is a macro that out puts a character to a file stream.

                            Syntax: int putc(int c,FILE *stream);

Functions:

1)fgetc():- It is a function. It gets a character from a file stream.

                            Syntax: int fgetc(FILE *stream);

2)fputc():- It is a function. It outputs a character to a file stream.

                            Syntax: int fputc (int c, FILE *stream);

Program:Write a program to create a text file and store data into that file from keyboard
#include<stdio.h>
#include<conio.h>
void main()
{
  FILE *fp;
  char ch;
  clrscr();
  fp=fopen("a.txt","w");
  printf("Enter the data into file(ctrl+z to stop)\n");
  ch=getchar();
  while(ch!=EOF)
  {
    putc(ch,fp);
   ch=getchar();
  }
  fclose(fp);
  printf("data stored successfully");
  getch();
}
Program:Write a program to open a text file read data into that file display on the screen.
#include<stdio.h>
#include<conio.h>
void main()
{
  FILE *fp;
  char ch;
  clrscr();
  fp=fopen("a.txt","r");
  printf("reading data from file: \n");
  ch=getc(fp);
  while(ch!=EOF)
  {
    printf("%c",ch);
   ch=getc(fp);
   delay(100); //dos.h
  }
  fclose(fp);
  getch();
}
Program:Write a program to accept any file name and display all contents in the given file
#include<stdio.h>
#include<conio.h>
#include<dos.h>
void main()
{
  FILE *fp;
  char st[20],ch;
  clrscr();
  printf("Enter any file name:");
  gets(st);
  fp=fopen(st,"r");
  if(fp==NULL)
  {
    printf("File not found");
    getch();
    exit(0);
  }
  ch=getc(fp);
  while(ch!=EOF)
  {
    printf("%c",ch);
    ch=getc(fp);
    delay(20);
  }
  fclose(fp);
  getch();
}

Rewind: It repositions file pointer file streams beginning

            Syntax: void rewind(FILE *stream);

Program:
#include<stdio.h>
#include<conio.h>
void main()
{
  FILE *fp;
  char ch;
  clrscr();
  fp=fopen("text.txt","w+");
  printf("Enter data into file(ctrl+z to stop)\n");
  ch=getchar();
  while(ch!=EOF)
  {
    fputc(ch,fp);
    ch=getchar();
  }
  printf("\nReading data from file\n");
  rewind(fp);
  ch=fgetc(fp);
  while(ch!=EOF)
  {
    printf("%c",ch);
   ch=fgetc(fp);
  }
  fclose(fp);
  getch();
}

EOF:-  A constant indicating that end of file has been reached on a file. To get this character from keyboard press  ctrl+z.

fgets():-It gets string from file stream.

                                Syntax: char *fgets(char *s,int n,FILE *stream);

Remarks:-

  • fgets    :                reads characters from stream into the strings. It stops when it reads either

n – 1 characters or a new line character, whichever comes first.

fputs():-It outputs a string to file stream.

                                Syntax: int fputs(const char *s,FILE *stream);

Remarks:-

  • fputs      :            copies the null-terminated string s to the given output stream. It does not append a new line character, and the terminating null character is not copied.

feof():-It is a Macro that tests if end of file has been reached on a stream.

                                Syntax: int  feof(FILE *stream);

returned value:-

  • Returns non-zero if an end-of-file indicator was detected on the last input operation on the named stream.
  • Returns 0 if end-of-file has not been reached.
Program:
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
  FILE *fp;
  char st[80];
  clrscr();
  fp=fopen("str.txt","a+");
  printf("Enter string data into file('end' to stop)\n");
  gets(st);
  while(strcmpi(st,"end")!=0)
  {
    fputs(st,fp);
    fputs("\n",fp);
   gets(st);
  }
  rewind(fp);
  printf("Reading data from file\n");
  fgets(st,80,fp);
  while(!feof(fp))//while(feof(f)==0)But this is not efficient
  {
    printf("%s",st);
    fgets(st,80,fp);
  }
  fclose(fp);
  getch();
}

fscanf():-

              It scans and formats input from a file stream.

             Syntax: int fscanf (FILE *stream,const char *format [, address, …]);

fprintf():-

               It sends formatted output to the file stream.

             Syntax: int fprintf (FILE *stream, const char *format [, argument, …]);

NOTE:-In fprintf (or) fscanf, between formats atleast one space is neccessary.

Program:
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
  FILE *fp;
  int eno;
  char ename[20];
  float sal;
  clrscr();
  fp=fopen("emp.txt","w");
  printf("Enter eno:");
  scanf("%d",&eno);
  printf("Enter ename:");
  fflush(stdin);
  gets(ename);
  printf("Enter salary");
  scanf("%f",&sal);
  fprintf(fp,"%d %s %.2f",eno,ename,sal);
  fclose(fp);
  printf("Record is saved successfully");
  getch();
}

ftell():- It Returns the current file pointer.

             Syntax: long ftell(FILE *stream);

fseek():- It repositions the file pointer of a stream.

            Syntax: int fseek(FILE *stream,long offset,int whence);

Argument  What It Is/Does

stream   Stream whose file pointer fseek sets

 offset   Difference in bytes between whence (a file pointer position) and new position. For text mode streams, offset should be 0 or a value returned by ftell.

 whence   One of three they are

 Constant                          Value                     File location

  SEEK_SET   0                                              Seeks from beginning of file

 SEEK_CUR    1                                              Seeks from current position SEEK_END        2                                              Seeks from end of file       

Program:
#include<stdio.h>
#include<conio.h>
void main()
{
  FILE *fp;
  char ch;
  clrscr();
  fp=fopen("a.txt","w");
  printf("Current file pointer position:%d",ftell(fp));
  printf("Enter data into file(ctrl+z to stop)\n");
  ch=getchar();
  while(ch!=EOF)
  {
    fputc(ch,fp);
   ch=getchar();
  }
  printf("Present file pointer position:%d",ftell(fp));
  fseek(fp,-10,SEEK_CUR);
  printf("\nNew file pointer position:%d",ftell(fp));
  fclose(fp);
  getch();
}

BINARY FILES

putw():-It outputs an integer on a stream.

            Syntax: int putw(int w,FILE *stream);

getw():-It gets an integer from stream.

                Syntax: int getw(FILE *stream);

Program:
#include<stdio.h>
#include<conio.h>
void main()
{
  FILE *fp;
  int n;
  clrscr();
  fp=fopen("num.dat","a+b");
  printf("\nEnter integer data into file(ctrl +Z to stop)\n");
  scanf("%d",&n);
  while(n!=0)
  {
    putw(n,fp);
   scanf("%d",&n);
  }
  fseek(fp,0,0);
  printf("\n Reading data from file :\n");
  n=getw(fp);
  while(!feof(fp))
 {
   printf("%d\n",n);
   n=getw(fp);
 }
 fclose(fp);
 getch();
}

fwrite():-It appends specified no of equal sized data items to an output file.

            Syntax: size_t fwrite(const void *ptr, size_t size, size_t n, FILE*stream);

fread():-It reads a specified no of equal sized data items from an input streaminto a block.

            Syntax: size_t fread(void *ptr, size_t size, size_t n, FILE *stream);

Argument  What It Is/Does

ptr                      Points to a block into which data is read/write

size                     Length of each item read/write, in bytes

n                          Number of items read/write

stream                Points to input/output stream

 remove():- It is a Macro that removes a file

               Declaration:  int remove(const char *filename);

rename():- It Renames a file

               Declaration:  int rename(const char *oldname, const char *newname);

Program:
#include<stdio.h>
#include<conio.h>
struct item
{
  int ino;
  char iname[20];
  float cost;
};
void main()
{
  FILE *fp;
  struct item it;
  clrscr();
  fp=fopen("item.dat","wb");
  printf("Enter item number:");
  scanf("%d",&it.ino);
  printf("Enter item name:");
  fflush(stdin);
  gets(it.iname);
  printf("Enter cost:");
  scanf("%f",&it.cost);
  fwrite(&it,sizeof(it),1,fp);
  fclose(fp);
  printf("Record saved successfully");
  getch();
}

COMMAND LINE ARGUMENTS

It is a parameter supplied to a program when the program is invoked. This Parameter may represent a file name.Then the program should process. Command line arguments are typed by the user. The first argument is always the file name.

We know that every C program should have one main function and it can take arguments like other functions. If you work with command line arguments,The main function can take two arguments called “argc” and “argv”. And the information contained in the command line is processed on to the program

through these arguments.

The variable “argc” is an argument counter, that counts the no of arguments on the command line.

The variable “argv” is an argument vector, and represents an array of character pointers that points to the command line arguments. The size of this array will be equal to the value of “argc”.

Program:
#include<stdio.h>
#include<conio.h>
void main(int argc,char *argv[])
{
  FILE *fp;
  char ch;
  if(argc!=2)
  {
    printf("Invalid arguments");
    exit(0);
  }
  fp=fopen(argv[1],"w");
  ch=getchar();
  while(ch!=EOF)
  {
    putc(ch,fp);
    ch=getchar();
  }
  fclose(fp);
  printf("File is counted");
}
Follow Us On