Skip to main content

Files in C


A file is a repository of data that is stored in a permanent storage media, mainly in secondary memory. In order to use the files we should learn how to read information from a file and how to write information into a file.
A very important concept in C is the stream.The stream is a common logical interface to the various devices( files).A stream is linked to a file while using an open operation. A stream is disassociated from a file while using a close operation. The current location, also referred to as the current position, is the location in a file where the next fie access will occur.There are two types of streams text and binary.
The following are some difference between text and binary files
·         Text file is human readable because everything is stored in terms of text. In binary file everything is written in terms of 0 and 1, therefore binary file is not human readable.
·         A newline(\n) character is converted into the carriage return-linefeed combination before being written to the disk. In binary file, these conversions will not take place.
·         In text file, a special character, whose ASCII value is 26, is inserted after the last character in the file to mark the end of file. There is no such special character present in the binary mode files to mark the end of file.
·         In text file, the text and characters are stored one character per byte. For example, the integer value 1245 will occupy 2 bytes in memory but it will occupy 5 bytes in text file. In binary file, the integer value 1245 will occupy 2 bytes in memory as well as in file.
Using files in C
There are four steps in using files
Declare a file pointer variable
Open a file using fopen() function
Process the file using suitable functions
Close the file using fclose() function

Declare a file pointer variable
To access any file, we need to declare a pointer to FILE structure and then associate it with the particular file. This pointer is referred to as file pointer.
Syntax for declaring file pointer
                                                                              FILE * fp;
A pointer to FILE structure contains information, such as size, current file pointer position, type of file etc., to perform operation on the file.Opening a file function
Open a file using fopen() function
The fopen() function takes two arguments, the name of the file and the mode in which the file is to be opened. Mode specify the purpose of opening the file i.e, whether for reading or writing.
Syntax for opening the file in C
              fp = fopen(char *filename,char *mode);
When fopen() function opens a file in memory, it returns a pointer to this particular file. If fopen() function can't open the file then it will return NULL.
Example for opening a text file for reading in C
       void main()
       {
              FILE *fp;
              fp = fopen("file1.txt","r");      //statement 1
              if(fp == NULL)
              {
                     printf("\nCan't open file or file doesn't exist.");
                     exit(0);
              }
In the above example, statement 1 will open an existing in text mode and return a pointer to file. If file will not open, an appropriate message will be displayed.
File opening modes
Mode
Meaning
r
Open a text file for reading
w
Create a text file for writing
a
Append to a text file
rb
Open a binary file for reading
wb
Open a binary file for writing
ab
Append to a binary file
r+
Open a text file for read/write
w+
Create  a text file for read/write
a+
Append or create a text file for read/write
r+b
Open a binary file for read/write
w+b
Create a binary file for read/write
a+b
Append a binary file for read/write

Note: The complete path of the file must be specified, if the file is not in the current directory. Most of the functions prototype for file handling is mentioned in stdio.h.
Close the file using fclose() function
When the reading or writing of a file is finished, the file should be closed properly using fclose() function. The fclose() function does the following tasks:
Flushes any unwritten data from memory.
Discards any unread buffered input.
Frees any automatically allocated buffer
Finally, close the file.
Syntax for closing the file in C

              int fclose( FILE* );
Example for closing the file in C
       void main()
       {
              FILE *fp;
              fp = fopen("file1.txt","r");
              if(fp == NULL)
              {
                     printf("\nCan't open file or file doesn't exist.");
                     exit(0);
              }
                    - - - - - - - - - -
                    - - - - - - - - - -
              fclose(fp);
       }
Note: A stream’s buffer can be flushed without closing it by using the fflush() library function.The flushall() command flush all open streams.

Working with Text files
The following functions provides facility for reading and writing files
Reading
Writing
fscanf()
fprintf()
fgets()
fputs()
fgetc()
fputc()
fread()
fwrite()

Character Input and Output
Characters or a line (sequence of characters terminated by a newline) can be written or read from a file using following function.
putc()  function
The library function putc() writes a single character to a specified stream.Its prototype is
int putc(int ch,FILE *fp);
Eg:
char c=’x’;
FILE *fp=fopen(“abc.txt”,”w”);
putc(c,fp); // char x is written to file abc.txt.
fputs() function
To write a line of characters to a stream, the library function fputs() is used.Its prototype is
char fputs(char *str,FILE *fp);
Eg:
char str[]=”cek”;
FILE *fp=fopen(“abc.txt”,”w”);
fputs(str,fp); // string cek is written into file abc.txt
getc() and fgetc()
The function getc() and fgetc() are identical and can be used interchangeably. They input a single character from a specified stream.Its prototype is
int getc(FILE *fp);
Eg:
FILE *fp=fopen(“abc.txt”,”r”);
int c;
c=fgetc(fp); // reads a character

fgets() function
fgets() is a line oriented function for reading from a file.Its prototype is
char *fgets(char *str,int n, FILE *fp);
Eg:
FILE *fp=fopen(“abc.txt”,”r”);
char line[60];
char *c;
c=fgets(line,60,fp);
The other two file handling functions to be covered are fprintf() and fscanf().These functions operate exactly like printf() and scanf() except that they work with files. Their prototypes are
int fprintf(FILE *fp, const char *control-string,…);
int fscanf(FILE *fp, const char *control-string,…);
Eg:
FILE *fp=fopen(“abc.txt”,”w”);
fprintf(fp,”%s”,”cek”);
FILE *fp=fopen(“abc.txt”,”r”);int n;
fscanf(fp,”%d”,&n);
Binary Files and Direct File I/O
The operations performed on binary files are similar to text files since both types of files can essentially be considered as stream of bytes. In fact the same functions are used to access files in C. When a file is opened, it must be designated as text or binary and usually this is the only indication of the type of file being processed.
Direct I/O is used only with binary-mode files. With direct output, blocks of data are written from memory to disk and in direct input block of data are read  from disk to memory.For example, a single direct-output function can write an entire array to disk and a single direct input function call can read the entire array from disk back to memory.
The C file system includes two important functions for direct I/O: fread() and fwrite().Their prototypes are
size_t fread(void *buffer, size_t size,size_t num,FILE *fp)
size_t fwrite(void *buffer, size_t size,size_t num,FILE *fp)

The fread() function reads from the file associated with fp, num number of objects, each object size in bytes, into buffer pointed to by buffer.fwrite() function is the opposite of fread().It writes to files associated with fp,num number of objects, each object size in bytes, from the buffer pointed to by buffer.

Sample Programs

Read and display a file character by character using getc function
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
int ch;
fp=fopen("a.txt","r");
if(fp==NULL)
  {
  printf("Error opening file..");
  exit(1);
   }
ch=getc(fp);
while(ch!=EOF)
{
putchar(ch);
ch=getc(fp);
}
fclose(fp);
}
Reading line by line from a file using fgets
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
char * ch;
char line[80];
fp=fopen("a.txt","r");
if(fp==NULL)
  {
  printf("Error opening file..");
  exit(1);
   }
do
{
ch=fgets(line,80,fp);
if ( ch !=NULL)
 printf("%s",ch);
}
while(ch!=NULL);
fclose(fp);
}
Counting number of lines, characters and words in a file
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
int ch;
int nl=0,nc=0,nw=0;
fp=fopen("a.txt","r");
if(fp==NULL)
  {
  printf("Error opening file..");
  exit(1);
   }
ch=getc(fp);
while(ch!=EOF)
{
if (ch=='\n') nl++;
if(ch==' ') nw++;
nc++;
ch=getc(fp);
}
fclose(fp);
printf("Number of lines=%d, Number of characters = %d,Number of words=%d\n",nl,nc,nw+nl);
}
cheking whether two files are identical or different
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp1,*fp2;
int ca,cb;
char fname1[50],fname2[50];
printf("Enter the first file name...\n");
scanf("%s",fname1);
printf("Enter the second file name...\n");
scanf("%s",fname2);
fp1=fopen(fname1,"r");
fp2=fopen(fname2,"r");
if(fp1==NULL)
  {
  printf("Error opening file1..");
  exit(1);
   }
else if(fp2==NULL)
   {
    printf("Error opening file2..");
    exit(1);
   }
else
{
ca=getc(fp1);
cb=getc(fp2);
while(ca!=EOF && cb!=EOF && ca==cb)
{
ca=getc(fp1);
cb=getc(fp2);
}
fclose(fp1);
fclose(fp2);
if(ca==cb)
printf("Files are identical\n");
else if (ca!=cb)
printf("Files are different \n");
}
}
copy one file to another character by character using getc and putc function
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp1,*fp2;
int ch;
char fname1[50],fname2[50];
printf("Enter the source file name...\n");
scanf("%s",fname1);
printf("Enter the destination file name...\n");
scanf("%s",fname2);
fp1=fopen(fname1,"r");
fp2=fopen(fname2,"w");
if(fp1==NULL)
  {
  printf("Error opening source file..");
  exit(1);
   }
else if(fp2==NULL)
   {
    printf("Error opening destination file..");
    exit(1);
   }
else
{
ch=getc(fp1);
while(ch!=EOF)
{
putc(ch,fp2);
ch=getc(fp1);
}
fclose(fp1);
fclose(fp2);
printf("Files succesfully copied\n");
}
}
copy one file to another after replacing lower case letters with corresponding uppercase letters.
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp1,*fp2;
int ch;
char fname1[50],fname2[50];
printf("Enter the source file name...\n");
scanf("%s",fname1);
printf("Enter the destination file name...\n");
scanf("%s",fname2);
fp1=fopen(fname1,"r");
fp2=fopen(fname2,"w");
if(fp1==NULL)
  {
  printf("Error opening source file..");
  exit(1);
   }
else if(fp2==NULL)
   {
    printf("Error opening destination file..");
    exit(1);
   }
else
{
    ch=getc(fp1);
    if(islower(ch)) ch=toupper(ch);
    while(ch!=EOF)
    {
    putc(ch,fp2);
    ch=getc(fp1);
    if(islower(ch)) ch=toupper(ch);
    }
fclose(fp1);
fclose(fp2);
printf("Files succesfully copied\n");
}
}
copy one file to another line by line using fgets and fputs function
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp1,*fp2;
int ch;
char fname1[50],fname2[50],t[80];
printf("Enter the source file name...\n");
scanf("%s",fname1);
printf("Enter the destination file name...\n");
scanf("%s",fname2);
fp1=fopen(fname1,"r");
fp2=fopen(fname2,"w");
if(fp1==NULL)
  {
  printf("Error opening source file..");
  exit(1);
   }
else if(fp2==NULL)
   {
    printf("Error opening destination file..");
    exit(1);
   }
else
{
while((fgets(t,sizeof(t),fp1)!=NULL))
{
fputs(t,fp2);
}
fclose(fp1);
fclose(fp2);
printf("Files succesfully copied\n");
}
}
writing into a file using fprintf
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
int ch;

fp=fopen("a.txt","w");
if (fp==NULL)
  {
    printf("error opening file..\n");
    exit(1);
   }
else
  {

   fprintf(fp,"%s","Welcome\n");
   fprintf(fp,"%s","to file handling in C\n");
   fclose(fp);
  }
}
reading numbers from a file and separating even and odd numbers
into two different files
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp,*fpe,*fpo;
int n;
fp=fopen("num.dat","r");
fpe=fopen("enum.dat","w");
fpo=fopen("onum.dat","w");
if (fp==NULL||fpe==NULL||fpo==NULL)
  {
    printf("error opening file..\n");
    exit(1);
   }
else
  {
while(fscanf(fp,"%d",&n)==1)
   {
    if ( n%2==0)
     fprintf(fpe,"%d\n",n);
  else
    fprintf(fpo,"%d\n",n);
   }
fclose(fp);
fclose(fpe);
fclose(fpo);
}
}
 reading an array and writing to a file using fwrite and reading the file 
using fread
#include <stdio.h>
#include <stdlib.h>
#define SIZE 10
int main()
{
int i,a[SIZE],b[SIZE];
FILE *fp;
printf("Enter 10 elements in array a...\n");
for(i=0;i<10;i++)
  scanf("%d",&a[i]);
fp=fopen("num.dat","w");
if(fp==NULL)
 {
 printf("error opening file..\n");
 exit(1);
 }
fwrite(a,sizeof(int),SIZE,fp);
fclose(fp);
/*opening the file and reading to array b*/
fp=fopen("num.dat","r");
if(fp==NULL)
 {
 printf("error opening file..\n");
 exit(1);
 }
fread(b,sizeof(int),SIZE,fp);
printf("array b is...\n");
for(i=0;i<10;i++)
 printf("%d\n",b[i]);
fclose(fp);
}
Program for writing struct to file using fwrite
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct person
{
    int id;
    char fname[20];
    char lname[20];
};
int main ()
{
    FILE *outfile;
    
    // open file for writing
    outfile = fopen ("person.dat", "w");
    if (outfile == NULL)
    {
        fprintf(stderr, "\nError opend file\n");
        exit (1);
    }
    struct person input1 = {1, "rohit", "sharma"};
    struct person input2 = {2, "mahendra", "dhoni"};
       // write struct to file
    fwrite (&input1, sizeof(struct person), 1, outfile);
    fwrite (&input2, sizeof(struct person), 1, outfile);
     if(fwrite != 0)

        printf("contents to file written successfully !\n");
    else
        printf("error writing file !\n");
    return 0;
}
Program for reading struct using fread
This program will read the file person.dat file in the previous program.
#include <stdio.h>
#include <stdlib.h>
 // struct person with 3 fields
struct person
{
    int id;
    char fname[20];
    char lname[20];
};
int main ()
{
    FILE *infile;
    struct person input;
     
    // Open person.dat for reading
    infile = fopen ("person.dat", "r");
    if (infile == NULL)
    {
        fprintf(stderr, "\nError opening file\n");
        exit (1);
    }
       // read file contents till end of file
    while(fread(&input, sizeof(struct person), 1, infile))
        printf ("id = %d name = %s %s\n", input.id,
        input.fname, input.lname);
    return 0;

}
Random Access To File
There is no need to read each record sequentially, if we want to access a particular record. C supports these functions for random access file processing.
fseek()
ftell()
rewind()
fseek()
This function is used for seeking the pointer position in the file at the specified byte.
Syntax: 
fseek(FILE *fp,long offset,int position)
Where
fp-file pointer ---- It is the pointer which points to the file.
offset -displacement ---- It is positive or negative.This is the number of bytes which are skipped backward (if negative) or forward( if positive) from the current position.This is attached with L because this is a long integer.
Pointer position:
This sets the pointer position in the file.
Value     Pointer position
0               Beginning of file.
1               Current position
2               End of file
Ex:
1) fseek( p,10L,0)
0 means pointer position is on beginning of the file,from this statement pointer position is skipped 10 bytes from the beginning of the file.
2)fseek( p,5L,1)
1 means current position of the pointer position.From this statement pointer position is skipped 5 bytes forward from the current position.
3)fseek(p,-5L,1)
From this statement pointer position is skipped 5 bytes backward from the current position.
ftell()
This function returns the value of the current pointer position in the file.The value is count from the beginning of the file.
Syntax: long ftell(FILE *fptr);
Where fptr is a file pointer.r
rewind()
This function is used to move the file pointer to the beginning of the given file.
Syntax:void rewind(FILE *fptr);
Where fptr is a file pointer.

Example program for fseek():
Write a program to read last ‘n’ characters of the file using appropriate file functions(Here we need fseek() and fgetc()).
#include<stdio.h>

#include<conio.h>

void main()

{

     FILE *fp;

     char ch;

     clrscr();

     fp=fopen("file1.c", "r");

     if(fp==NULL)

        printf("file cannot be opened");

     else

    {

            printf("Enter value of n  to read last ‘n’ characters");
            scanf("%d",&n);

            fseek(fp,-n,2);

            while((ch=fgetc(fp))!=EOF)

            {

                 printf("%c\t",ch);

            }

      }


    fclose(fp);
}


Comments

Popular posts from this blog

KTU C programming question paper and evaluation scheme

APJ ABDUL KALAM TECHNOLOGICAL UNIVERSITY SECOND SEMESTER B.TECH DEGREE EXAMINATION, MAY 2017 CS 100 COMPUTER PROGRAMMING (CS, IT) SCHEME OF EVALUATION
PART A 1 An identifier is a sequence of characters invented by the programmer or to identify or name a specific object. The sequence of characters may be letters, digits, and special character ‘_’known as an underscore Rules: i)Identifiers should start with alphabets. ii)Identifiers are case sensitive iii)A numeric digit should not be the first character iv)Identifier name should not be a keyword v)Identifier may be of any reasonable length 1mark






2mark 2 Associativity defines the direction, left to right or right to left in which operator act upon its operands Unary operators have associativity is from right to left. For examplein the expression &--x, pre decrement works first and then address of operator works Direction + example<

Strings in C

Strings in C Strings are defined as an array of characters. The difference between a character array and a string is the string is terminated with a special character ‘\0’. Declaration of strings: Declaring a string is as simple as declaring a one dimensional array. Below is the basic syntax for declaring a string. charstr_name[size]; In the above syntax str_name is any name given to the string variable and size is used define the length of the string, i.e the number of characters strings will store. Please keep in mind that there is an extra terminating character which is the Null character (‘\0’) used to indicate termination of string which differs strings from normal character arrays. Initializing a String: A string can be initialized in different ways. We will explain this with the help of an example. Below is an example to declare a string with name as str and initialize it with “cek”. 1. charstr[] = "cek"; 2. charstr[50] = "cek"; 3. charstr[] = {'c','…