C-Tutorial: Files

Latest

Showing posts with label Files. Show all posts
Showing posts with label Files. Show all posts

Thursday, 10 November 2016

fprintf() and fscanf() functions in C

Thursday, November 10, 2016 0
fprintf() and fscanf() functions


            Most compilers support two functions namely fprintf() and fscanf() functions, that can handle a group of mixed data simultaneously.  The functions fprintf() and fscanf() perform I/O operations that are identical to printf() and scanf() functions, except that they work on files.

fscanf() funcnton:       fscanf() function is used to read mixed data simultaneously form a given file.  The general format of the fscanf() function is:

            Syntax:            fscanf(FilePointer, “ControlString”, List);

Where,
            FilePointer associated with the file that has been opened for reading.
            ControlString consists of format specification for the items in the list.
            List may include variables, constants, strings etc.,
Function returns EOF marker whenever end of the file has been reached.

fprintf() function:        fprintf() function is used to write mixed data simultaneously into a given file.  The general format of the fpritnf() function is:

            Syntax:            fprintf(FilePointer, “ControlString”, List);

Where,
            FilePointer associated with the file that has been opened for writing.
            ControlString consists of output format specification for the items in the list.
            List may include variables, constants, strings etc.,

           
/* WRITE A PROGRAM TO CREATE A FILE THAT CONTAINS INVENTORY DETAILS LIKE PRODUCT NUMBER, PRODUCT NAME AND PRODUCT COST.  READ THE SAME DATA FROM THE FILE AND PRINT IT */

#include<stdio.h>
#include<conio.h>
struct product
{
            int id;
            char name[20];
            float price;
}p;
main()
{
            char flag='y';
            FILE *f;
            clrscr();
            f=fopen("product.dat","w");
            while(flag=='y')
            {
               printf("\nEnter product id:");
               scanf("%d",&p.id);
               fflush(stdin);
               printf("\nEnter product name:");
               gets(p.name);
               printf("\nEnter product cost:");
               scanf("%f",&p.price);
               fprintf(f,"%d\t%s\t%f\n",p.id,p.name,p.price);
               printf("\nDo you want add another record(y/n):");
               fflush(stdin);
               flag=getchar();
            }
            fclose(f);
            f=fopen("product.dat","r");
            if(f==NULL)
            {
                        printf("\nFILE OPENING ERROR");
                        exit();
            }
            printf("\nPRODUCT DETAILS ARE:\n");
            while((fscanf(f,"%d%s%f",&p.id,p.name,&p.price))!=EOF)
            printf("\n%d\t%s\t%.2f",p.id,p.name,p.price);
            fclose(f);

}
Read More

FILE ACCESSING TECHNIQUES (or) FILE TYPES

Thursday, November 10, 2016 0
FILE ACCESSING TECHNIQUES (or) FILE TYPES

            Every open file has an associated file position indicator, which describes where read and write operations take place in the file.  The position is always specified in bytes from the beginning of the file.

            When a file is opened in either read (or) write mode, the position indicator is always at beginning of the file i.e., at position ‘0’.  If the file is opened in append mode, the position indicator is at the end of the file.
           
File accessing techniques can be classified into two types as:

1.                  Sequential file processing
2.                  Random access file processing

1. Sequential File Processing:           In sequential file processing, the file pointer moves character by character without skipping data. i.e., read or write operations performed sequentially.  getc(), putc(), fgets(), fputs() etc., functions support sequential file processing.

2. Random Access File Processing:              In random access file processing, the file pointer can change from one location to another location according to user requirements.  Here, operations are performed in random access manner.  Most important functions used in random access file processing are:

            a)         fseek()
            b)         ftell()
            c)         rewind()

a)  fseek() function:    fseek() function is used to move the position indicator to a desired location within the file.  The general format of the fseek() function is:

            Syntax:            fseek(FilePointer, OffSet, Position);

Where,
Ø  OffSet is the number of bytes to be moved and it must be long integer.  The value may be positive of negative.  If the OffSet value be positive, file pointer moves to forward direction; otherwise, file pointer moves to backward direction.
Ø  Position specifies the starting position in the file to move.  Position can take any one of the following three values.


VALUE
MEANING

0
Beginning of File
1
Current Position
2
End of File

When the operation is successful, fseek() function returns zero; otherwise, it return -1.

Examples:

1.         fseek(fp,0L,0)             -           Go to beginning of the file
2.         fseek(fp,0L,1)             -           Stay at the current position
3.         fseek(fp,0L,2)             -           Go to end of the file
4.         fseek(fp,m,0)               -           Move to m bytes from beginning of the file
5.         fseek(fp,m,1)               -           Go to forward by m bytes from current position
6.         fseek(fp,-m,2)             -           Go to backward by m bytes from the end of file.

b)  ftell() function:      ftell() function is used to return the current position of the file pointer in the file.  The general format of the ftell() function is:

            Syntax:            N = ftell(FilePointer);

Where,
            N is a long integer variable.

Function returns current position (in bytes) as long integer value.  If any error encountered, then the function returns -1.


c)  rewind() function:             rewind() function is used to reset the file pointer to beginning of the file.  The general format of the rewind() function is:

            Syntax:            rewind(FilePointer);


Function reset the file pointer at the beginning of the file.

WRITE A PROGRAM TO PRINT THE CONTENTS OF A FILE IN REVERSE ORDER 

#include<stdio.h>
main()
{
            FILE *fp;
            long n,i;
            char ch;
            clrscr();
            fp=fopen("den.txt","r");
            if(fp==NULL)
            {
                        printf("\nFile Opening Error");
                        exit();
            }
            fseek(fp,-1L,2);
            n=ftell(fp);
            printf("\nFile Contents in Reverse Order:\n");
            for(i=1;i<=n+1;i++)
            {
                        fseek(fp,-i,2);
                        putchar(fgetc(fp));
            }
            fclose(fp);
}
Read More

fread() and fwrite() functions in C

Thursday, November 10, 2016 0
fread() and fwrite() functions:

fread() and fwrite() functions are used to read and write data in binary format.  The general formats of fread() and fwrite() functions are:

            Syntax:            fread(&x, sizeof(x), 1, FilePointer);
                                    fwrite(&x, sizeof(x), 1, FilePointer);

Here,
            The first argument is address of the argument.
            The second argument is size of the argument in bytes.
            The third argument is number of arguments read or write at one time.
            The final argument is the FilePointer.


/* WRITE A PROGRAM TO DEMONSTRATE THE DIFFERENCE BETWEEN TEXT MODE Vs BINARY MODE FORMATS */

#include<stdio.h>
main()
{
            int x;
            float y;
            char z='\n';
            FILE *fp;
            clrscr();
            fp=fopen("Exam.txt","w");
            printf("\nEnter One Integer and One Floating Number:\n");
            scanf("%d%f",&x,&y);
            fprintf(fp,"%d\n%f",x,y);
            fclose(fp);
            fp=fopen("Del.txt","wb");
            fwrite(&x,sizeof(x),1,fp);
            fwrite(&z,sizeof(z),1,fp);
            fwrite(&y,sizeof(y),1,fp);
            fclose(fp);

}
Read More

FILE FORMATS in C

Thursday, November 10, 2016 0
FILE FORMATS


            File formats can be categorized into two ways as: Text mode format and Binary mode format.  This classification arises at the time of opening the file.

            When a file is opened either in “r”, “w” or “a” modes, default file format is text mode format.  If the user wants to open the file in binary format, explicitly necessary to specify as “rb”, “wb”, or “ab”.

            There are three main differences raised between a text file and binary files.  Those are:
1.      Handling of new lines
2.      Representation of End-Of-File
3.      Storage of numbers.

1.         In text mode, a new line character is converted into the combination of carriage return – line feed before being written into the disk.
            In binary mode, conversions not take place.  A new line character is written into the disk as in the original format.

2.         In text mode, a special character is inserted after the last character in the file to mark the End-Of-File.  If this character is detected at any point in the file, then read function would return the EOF signal to the program.
            In binary format, there is no such special character present to mark the End-Of-File.  The binary mode files keep track of the End-Of-File from the number of characters present in the directory entry of the file.

3.         In text mode, while storing numbers in files, numbers are stored as string of characters.
            Consider a number 4523.
In memory, it occupies 2 bytes.  Whereas when the number placed on the disk, it would occupy 4 bytes as one byte per each character.  Since, it depends on magnitude of the number.
In such case, large amount of data storage in a disk file is inefficient.

            In binary mode, number would occupy same number of bytes on disk as it occupies in memory unit.  With this, the above number occupies only 2 bytes even on the disk file
Read More

getw() and putw() functions in C

Thursday, November 10, 2016 0
getw() and putw() functions:


            getw() and putw() are number oriented functions are used to read and write integer values on a given file.

getw() function:                      getw() function is used to read an integer value from a given file.  The general format of the getw() function is:

            Syntax:            getw(FilePointer);

This function receives FilePointer as an argument and returns next integer from the input file.  It returns EOF whenever end of file has been reached.

putw() function:          putw() function is used to write an integer value into the specified file.  The general format of the putw() function is:

            Syntax:            putw(N,FilePointer);

Where,
            N is an integer value to be written into the given file with FilePointer opened in write mode.

/* WRITE A PROGRAM TO CREATE AN INPUT DATA FILE WHICH CONTAINS A LIST OF INTEGERS.  READ THE SAME DATA FROM THE FILE AND WRITE EVEN AND ODD NUMBERS INTO TWO SEPARTE FILES */

#include<stdio.h>
#include<conio.h>
main()
{
            int item,n,i;
            FILE *f1,*f2,*f3;
            clrscr();
            f1=fopen("input.dat","w");
            printf("\nEnter how many numbers:");
            scanf("%d",&n);
            printf("\nEnter %d Numbers:",n);
            for(i=1;i<=n;i++)
            {
                        scanf("%d",&item);
                        putw(item,f1);
            }
            fclose(f1);

            f1=fopen("input.dat","r");
            if(f1==NULL)
            {
                        printf("\nFILE OPENING ERROR");
                        exit();
            }
            f2=fopen("even.dat","w");
            f3=fopen("odd.dat","w");
            while((item=getw(f1))!=EOF)
            {
                        if(item%2==0)
                                    putw(item,f2);
                        else
                                    putw(item,f3);
            }
            fcloseall();
            printf("\nEVEN NUMBERS ARE:");
            f2=fopen("even.dat","r");
            while((item=getw(f2))!=EOF)
            printf("%6d",item);
            fclose(f2);
            printf("\nODD NUMBERS ARE:");
            f3=fopen("odd.dat","r");
            while((item=getw(f3))!=EOF)
            printf("%6d",item);
            fclose(f3);

}
Read More

fgets() and fputs() functions in C

Thursday, November 10, 2016 0
 fgets() and  fputs() functions in C


            fgets() and fputs() functions are string oriented functions that can be handled an entire line as a string at a time.

fgets() function:                      fgets() function is used to read a set of characters as a string from a given file.  The general format of the fgets() function is:

            Syntax:            fgets(char[], int, FilePointer);
Where,
            The first argument is the character array where the string is stored.
            The second argument is the maximum size of the string.
            The third argument is the FilePointer of the file to be read.
The function returns a NULL pointer if the end of file has been reached.

fputs() function:          fputs() function is used to write a string into a file.  The general format of the fputs() function is:

            Syntax:            fputs(char[], FilePointer);

Where,
            The first argument is the character array to be written into the file.
            The second argument is the FilePointer of the file to write.
The function returns a non-negative value on successful completion; otherwise, it returns EOF.

/* COPY THE CONTENTS OF ONE FILE TO ANOTHER FILE LINE BY LINE */

#include<stdio.h>
#include<string.h>
main()
{
            char ch[50];
            FILE *fp1,*fp2;
            clrscr();
            fp1=fopen("check.txt","r");
            if(fp1==NULL)
            {
                        printf("\nFILE OPENING ERROR");
                        exit();
            }

            fp2=fopen("ptr.txt","w");
            while((fgets(ch,sizeof(ch),fp1))!=NULL)
            fputs(ch,fp2);
            fclose(fp2);
            fclose(fp1);

}
Read More