File Management

C Tutorials

So why do we need FILES? What is the use of complicating the process of storing data? Lets us explore how we can handle files in C language

Here is the answer for all these questions.

  • The entire data is lost when computer is turned off or program is closed, but with the help of FILES we can permanently store data on the disk.
  • It becomes difficult to handle large amount of data using console oriented I/O operations.

Now we will study the basic file operations.

 

Table1

 

File functions and operations

 

 

CREATING FILE

A file is always accessed using a pointer of type FILE.

 

SYNTAX

FILE *fp;    /*declares a pointer of type FILE*/

Fp=fopen (“filename”,”mode”);

 

Above statement opens a file named “filename” if it already exists and creates if the file doesn’t exist and it assigns the pointer fp to the file. This statement also defines the purpose of opening file like if the user wants to read, write, append or combination of these. This process is taken care by “mode”.

 

 

Table2

 

Different modes and operations

 

 

CLOSING A FILE

It is a good practise to close files when all the required operation on it are finished.

Fclose (file_pointer);

 

 

INPUT AND OUTPUT OPERATIONS ON FILES

To read, write or append a file we need functions likewise we needed to write data on console and read from the keyboard.

 

Getc() function- used to read a character at time from the file. File must be opened in at least read mode.

Getc (file_pointer);

 

Putc() function- used to write one character on the file. File must be opened in at least read mode or append mode.

Putc (file_pointer);

 

Getw() and putw() functions: - are same as getc and putc but they are used only for integer values.

 

Fprintf()and fscanf() functions: - are similar to printf and scanf functions, the only difference is fprintf and fscanf writes on FILE and reads from FILE respectively.  Fprintf and fscanf takes file_pointer as an extra argument compared to printf and scanf.

Fprintf (fp,” control string”, list);

Fscanf (fp,” control string”, list);

 

 

RANDOM ACCESS TO FILE DATA

Till now we have learnt to access file from starting or at the end.

What if we want to access data from somewhere in between the file? For this we have fseek, ftell and rewind functions for our rescue.

 

Ftell() - is used to gather the relative position of file pointer from starting.

N=ftell (fp);

Here n would store the number of bytes or relative position of pointer with respect to start of file.

 

Rewind()- takes the file pointer to the start of file.

Rewind (fp);

 

Fseek()- this function is used to move the file pointer to a desired location.

Fseek (file_pointer, offset, position);

 

Here position takes either of following values:-

  • 0-      Beginning of file.
  • 1-      Current position of file.
  • 2-      End of file.

Offset specifies the number of position (bytes) to be moved from location specified by position.

Note:-fseek returns 0 after successful completion of task otherwise -1(minus 1).

 

 

Sample Program -

 

 

 

#include<stdio.h>

#include<conio.h>

#include<process.h>

 

read_file(FILE*,char*);

create_file(FILE*,char*);

write_file(FILE*,char*) ;

flush(FILE *);

void main()

{

FILE *read,*write;

char ch,*filename="file.txt";

clrscr();

 

 

do

{  clrscr();

   printf("\n  SELECT   "

                  "\n 1. read existing file"

                  "\n 2. create file"

                  "\n 3. write to file"

                  "\n 4. exit"

                  "\n Enter your choice(1-4)?");

     flush(stdin);

     ch=getchar();

   switch(ch)

                 {

                                case  '1' :read_file(read,filename);

                                                                  break;

                                case  '2' :create_file(write,filename);

                                                                  break;

                                case  '3' :write_file(write,filename);

                                                                  break;

                                case  '4' :exit(0);

                                                                  break;

                                default                 :printf("\n wrong choice");

                                                                  break;

 

                 }

}while(1);

 

 

}

 

//read file

read_file(FILE  *read,char *filename)

{

char ch;

read=fopen(filename,"r");

 

if(!read)

  printf("\n \"%s\" file could not be read!!---\n",filename);

else

 printf("\n \"%s\" file  opened successfully",filename);

printf("\n\n Press any key to view file contents..");

getch();

 

clrscr();

printf("\nCONTENTS OF \"%s\"\n",filename);

while(1)

{

ch=fgetc(read);

if(ch!=EOF)

 printf("%c",ch);

else

 break;

}

fclose(read);

getch();

}

//create file

create_file(FILE *write,char *filename)

{

write=fopen(filename,"w");

if(!write)

  printf("\n \"%s\" file could not be created/accessed!!---\n",filename);

else

 printf("\n \"%s\" file created/accessed successfully\n",filename);

fclose(write);

getch();

}

 

 

write_file(FILE *write,char *filename)

{

char ch;

write=fopen(filename,"a");

 

if(!write)

  printf("\n \"%s\" file could not be accessed!!---\n",filename);

else

 {

 printf("\nEnter text to write to file(tab to end):");

  flush(stdin);

  while((ch=getchar())!='\t')

  {putc(ch,write);}

 }

fclose(write);

getch();

}

 

flush(FILE *input)

{ char ch;

//while((ch=getc(input))!=0&&ch!=-1);

//scanf("%c%*[^\-1]",&ch);

//scanf("%*c");

//while(getchar()!=EOF);

rewind(stdin);

return 1;

 

 

Outputs will be as shown below:-

 

 

File management ouput 1

 

 

File management output 2

 

 

File management ouput 4

 

File management output 3

 

 

Download source code.