File

A file used to store the data which represents a sequence of bytes, It can be a text file or a binary file.

Files can be categorized as:
  1. Text file
  2. Binary file

File Operations
  1. Creating/Open a new file
  2. Reading/writing information to a file
  3. Closing a file

For File Operation in c use a structure pointer of file type to declare a file.
            FILE *fptr;

C provide Functions to support the various file operations



fopen()
Create a new file or open the existing file
fclose()
Close the file
getw()
Reads an integer from file
putw()
Writes an integer to file
getc()
Reads a character from file
putc()
Writes a character to file
fscanf()
Reads all type of data from file (int,char,float)
fprintf()
Writes all type of data to file (int,char,float)
fread()
Reads multiple data from file
fwrite()
Writes multiple data to file
fseek()
Set the position of pointer in file
ftell()
Tell the current position of pointer
rewind()
Moves the pointer  at the beginning of file






















Opening/Creating a File
The fopen() function is used to open or create a file.

            *fptr = FILE *fopen(const char *filename, const char *mode);

Here filename is name of the file and mode shows the purpose of opening the file.

*fptr is the FILE pointer which holds the reference of opened file.


fopen()
Create a new file or open the existing file
fclose()
Close the file
getw()
Reads an integer from file
putw()
Writes an integer to file
getc()
Reads a character from file
putc()
Writes a character to file
fscanf()
Reads all type of data from file (int,char,float)
fprintf()
Writes all type of data to file (int,char,float)
fread()
Reads multiple data from file
fwrite()
Writes multiple data to file
fseek()
Set the position of pointer in file
ftell()
Tell the current position of pointer
rewind()
Moves the pointer  at the beginning of file





















Closing File
The fclose() function is used to close the file.

            fclose(FILE *fptr);

Here fclose function close the file pointed by *fptr and reurn 0 on success.

Input/output operation on File (Read/Write to File)

putc() and getc() functions
The putc() function writes the character to the file
            putc(c, fptr);
Where c is a character and fptr is pointer to FILE.

Similarly getc is used to read a character from a file that has been opened in read mode
            c=getc(fptr);
Where c is a character and fptr is pointer to FILE. The getc will retorun an End-Of-File (EOF), when end of the file is reached.
The file pointer moves one by one character in putc and getc.

#include <stdio.h>
#include <stdlib.h>

void main()
{
            char ch, source_file[20]="t1.txt";
            FILE  *fptr;                                                     //File Pointer
            clrscr();

            fptr = fopen(source_file, "w+");                   //Opening/Creating a File

            if( fptr == NULL )
            {
                         printf("Press any key to exit...\n");
                         exit(EXIT_FAILURE);
            }
            while((ch=getchar())!=EOF)                                    //Writing to File using putc
            {
                        putc(ch,fptr);
            }
            fclose(fptr);                                                    //Closing File
            fptr=fopen(source_file,"r");
             while((ch=getc(fptr))!=EOF)                                  //Reading from File using getc
            {
                        printf("%c",ch);
             }
            fclose(fptr);
            getch();
}

putw and getw functions
The getw and putw functions are used to read and write integer values. It is useful when we have to work with only integer data.
            putw(n, fptr);
            n=getw(fptr);
Where n is an integer and fptr is file pointer.

fprintf and fscanf function
The fprintf and fscanf functions perform I/O operations that are similar to print and scanf functions, but they work on file.
            fprintf(fptr,”control string”,list);
            fscanf(fptr,”control string”,list);
where fptr is pointer to file and control string is output specifications for the listed items
like
            fprintf(fptr,”%s %d %f”,name,age,perc);
            fscanf(fptr, ”%s %d %f”,name,age,perc);
When the End Of File is reached it returns EOF.

#include<stdio.h>
#include<conio.h>
void main()
{
            char name[20],name2[20];
            int m1,m2,i;
            FILE *fptr;
            clrscr();
            fptr=fopen("s2.txt","w+");
            if(fptr==NULL)
            {
                        printf("error");
                        exit(1);
            }

            fscanf(stdin,"%s %d",name,m1);
            fprintf(fptr,"%s %d",name,m1);

            fclose(fptr);

            printf("\n Reading File\n");
            fptr=fopen("s2.txt","r+");

            fscanf(fptr,"%s %d",name2,m2);
            fprintf(stdout,"name:%s \nNo:%d",name2,m2);

            fclose(fptr);
            getch();

}

Reading and Writing Records (Structure) to file
fread and fwrite function
            fread(x,sizeof(x),1,*fptr);
            fwrite(x,sizeof(x),1,*fptr);
Where x is the data to read or write, sizeof will give the size of elements,and *fptr is pointer to FILE
The fread and fwrite functions are used in binary mode

#include<stdio.h>
#include<conio.h>
struct book
{
            int id;
            char name[20];
};
void main()
{
            struct book b1[3],b2[3];
            FILE *fptr;
            int i;
            clrscr();
            fptr=fopen("file.dat","wb");
            for(i=0;i<3;i++)
            {
                        fflush(stdin);
                        printf("insert id");
                        scanf("%d",&b1[i].id);
                        printf("insert name");
                        scanf("%s",b1[i].name);
            }
            fwrite(b1,sizeof(b1),1,fptr);
            fclose(fptr);
            fptr=fopen("file.dat","rb");
            fread(b2,sizeof(b2),1,fptr);
            for(i=0;i<3;i++)
            {
                        printf("\n %d %s",b2[i].id,b2[i].name);
            }
            fclose(fptr);
            getch();
}

Random Access to file
fseek() - It is used to move the control to different positions using fseek function.

ftell() - It tells the current position of cursor in file pointer.

rewind() - It moves control to beginning of the file.



//Program to find the size of file using fseek and ftell
#include<stdio.h>
#include<conio.h>

void main()
{
    FILE *fp;
    char ch;
    int size = 0;

    fp = fopen("MyFile.txt", "r");
    if (fp == NULL)
    {
        printf("\nFile unable to open ");
    }
    else
    {
        printf("\nFile opened ");
    }
    fseek(fp, 0, 2);    /* file pointer at the end of file */
    size = ftell(fp);   /* take a position of file pointer un size variable */
    printf("The size of given file is : %d\n", size);   
    fclose(fp);
}


//Program to copy  a file into another
#include <stdio.h>
#include <stdlib.h>

void main()
{
            char ch, source_file[20]="t1.txt", target_file[20]="t2.txt";
            FILE    *source, *target;
            clrscr();
           
            source = fopen(source_file, "w+");

            if( source == NULL )
            {
                              printf("Press any key to exit...\n");
                              exit(EXIT_FAILURE);
            }
            while((ch=getchar())!=EOF)
            {
                        putc(ch,source);
            }
            rewind(source);
            target = fopen(target_file, "r+");

            if( target == NULL )
            {
                  fclose(source);
                  printf("Press any key to exit...\n");
                  exit(EXIT_FAILURE);
            }

            while( ( ch = fgetc(source) ) != EOF )
            {
                  fputc(ch, target);
            }
            printf("File copied successfully.\n");
            printf("Reading Target File\n");
            rewind(target);
            while((ch=getc(target))!=EOF)
            {
                        printf("%c",ch);
            }
            fclose(source);
             fclose(target);

            getch();
}

Binary Files
Depending upon the way file is opened for processing, a file is classified into text file and binary file.
If a large amount of numerical data it to be stored, text mode will be insufficient. In such case binary file is used.
Working of binary files is similar to text files with few differences in opening modes, reading from file and writing to file.
Opening modes of binary files
Opening modes of binary files are rb, rb+, wb, wb+,ab and ab+. The only difference between opening modes of text and binary files is that, b is appended to indicate that, it is binary file.

Reading and writing of a binary file.
Functions fread() and fwrite() are used for reading from and writing to a file on the disk respectively in case of binary files.
Function fwrite() takes four arguments, address of data to be written in disk, size of data to be written in disk, number of such type of data and pointer to the file where you want to write.
fwrite(address_data,size_data,numbers_data,pointer_to_file);
Function fread() also take 4 arguments similar to fwrite() function as above.


0 comments:

Post a Comment