Ad Code

Responsive Advertisement

File in c language.

Types of Files in C 

-> There are two types of files are available in ‘C’ languages

Text file
-
-> Text File is Also Called as “Flat File“.
-
 Text File Format is Basic File Format in C Programming.
-
 - >Text File is simple Sequence of ASCII Characters.
-
->  Each Line is characterized by EOL Character (End of Line).
-
->  Text File have .txt Extension.
-
 Text File Format have little contains very little formatting.
-
 - > The precise definition of the .txt format is not specified, but typically matches the format
accepted by the system terminal or simple text editor.
-
->  Files with the .txt extension can easily be read or opened by any program that reads text and,
for that reason, are considered universal (or platform independent).
-
->  Text Format Contain Mostly English Characters

Binary File
-
->  Binary Files Contain Information Coded Mostly in Binary Format.
-
->  Binary Files are difficult to read for human.
-
->  Binary Files can be processed by certain applications or processors.
-
->  Only Binary File Processors can understand Complex Formatting Information Stored in
Binary Format.
-
 - >  Humans can read binary files only after processing.
-
 - >  All Executable Files are Binary Files.
Binary file is stored in Binary Format (in 0/1). This Binary file is difficult to read for humans.
So generally Binary file is given as input to the Binary file Processor. Processor will convert
binary file into equivalent readable file.


Some Examples of the Binary files:
1. Executable Files
2. Database files

Defining, Opening & Closing a File 
A file represents a sequence of bytes on the disk where a group of related data is stored. File is created
for permanent storage of data. It is a ready made structure.

File *fp; 
fp = fopen(“filename”,”mode”) ;

-> The first statement declares the variable fp as “pointer to the data type FILE”.

-> The second statement opens the file named and assigns an identifier to the FILE type pointer fp.

-> There are various files mode are available in ‘C’.

R :-> opens a text file in reading mode
W opens or create a text file in writing mode.

A :->  opens a text file in append mode.

r+ :-> opens a text file in both reading and writing mode.

w+ :-> opens a text file in both reading and writing mode.

a+ :-> opens a text file in both reading and writing mode.

Rb :-> opens a binary file in reading mode
Wb opens or create a binary file in writing mode.

Ab :-> opens a binary file in append mode
rb+ opens a binary file in both reading and writing mode.

wb+ :->  opens a binary file in both reading and writing mode.

ab+ :-> opens a binary file in both reading and writing mode.

Closing a File 
-> The fclose() function is used to close an already opened file. This ensures that all outstanding
information associated with the file is flushed out from the buffers and all the links to the file are
broken.

-> It prevents the accidental misuse of file.
fclose (file_pointer)
Read, Write & Append operations in a File

#include<stdio.h>
#include<conio.h>
main()
{
      FILE *fp;
      char ch;
      fp = fopen("one.txt", "w");
       printf("Enter data");
      while( (ch = getchar()) != EOF) {
 putc(ch,fp);
 }

     fclose(fp);
     fp = fopen("one.txt", "r");
     while( (ch = getc()) != EOF)
     printf("%c",ch);
     fclose(fp);
}


Write a C program to read name and marks of n number of students from user and store them in a file. 

 #include <stdio.h>
 int main()
{
      FILE *fptr;
      char name[50];
       int marks,i,n;
       printf("Enter number of students: ");
       scanf("%d",&n);
       fptr=(fopen("student.txt","w"));
       if(fptr==NULL){
       printf("Error!");
      exit(1);
 }

 for(i=0;i<n;++i)
 {
 printf("For student%d\nEnter name: ",i+1);
     scanf("%s",name);
     printf("Enter marks: ");
      scanf("%d",&marks);
       fprintf(fptr,"\nName: %s \nMarks=%d        \n",name,marks);
 }
 fclose(fptr);
 return 0;
}

Reading & Writing Records (Structures) to a File. 

#include<stdio.h>
#include<conio.h>
struct emp
{
 char name[10];
 int age;
};
void main()
{
      struct emp e;
      FILE *p,*q;
       p = fopen("one.txt", "a");
      q = fopen("one.txt", "r");
      printf("Enter Name and Age");
      scanf("%s %d", e.name, &e.age);
      fprintf(p,"%s %d", e.name, e.age);
      fclose(p);
 do
 {
      fscanf(q,"%s %d", e.name,& e.age);
      printf("%s %d", e.name, e.age);
 }
 while( !feof(q) );
 getch();
}

 Random Access of Files 

-> In file handling, if we want to access our data with specific position then we have to use with
random access of files. There are occasions, however, when we are interested in accessing only a
particular part of a file and not in reading the other parts. This can be achieved with the help of the
functions fseek, ftell, and rewind available in the I/O library.

ftell:- it takes a file pointer and return a number of type long, that corresponds to the current position.
This function is useful in saving the current position of a file, which can be used later in the program.
It takes the following form:

           n=ftell(fp); 
n would give the relative offset(in bytes) of the current position. This means that n bytes have
already been read (or written)..

Rewind: - It takes a file pointer and resets the pointer to the start of the file. For example, the
statement
rewind(fp);
n=ftell(fp)
would assign 0 to n because the file position has been set to the start of the the file by rewind.
Remember, the first byte in the file numbered as 0, second as 1, and so on. This function helps us in
reading a file more than once, without having to close and open the file. Remember that whenever a
file is opened for reading or writing, reading is done implicitly.


Fseek: - fseek function is used to move the file position to a desired location within the file it takes
the following form:

fseek(file_ptr,offset,position); 
file_ptr is a pointer to the file concerned , offset is a number or variable of type long, and position
is an integer number.

Value Meaning
0 Beginning of file
1 Current position
2 End of file

Example of fseek and ftell
#include <stdio.h>
int main ()
{
      FILE *fp;
      int len;
      fp = fopen("file.txt", "r");
      if( fp == NULL )
      {
           perror ("Error opening file");
           return(-1);
      }
 fseek(fp, 0, SEEK_END);
 len = ftell(fp);
 fclose(fp);
 printf("Total size of file.txt = %d bytes\n", len);
 return(0);
}


Example of Rewind 
void main(){
 FILE *fp;
 int i;
 clrscr();
fp = fopen("ONE.txt","r");
 for (i=1;i<=10;i++){
 printf("%c : %d\n",getc(fp),ftell(fp));
 fseek(fp,ftell(fp),0);
 if (i == 5)
 rewind(fp);
 }
 fclose(fp);
}

Example 
#include <stdio.h>
main()
{
        FILE *fp;
        long n;
        char c;
        clrscr();
      fp=fopen("random","w");
     while((c=getchar())!=EOF)
      putc(c,fp);
      printf("No of character enetered =     %ld\n",ftell(fp));
 fclose(fp);
 fp=fopen("random","r");
 n=0L;
 while(feof(fp)==0)
 {
        fseek(fp,n,0);/*position to (n+1) th       character*/
       printf("position of %c is     %ld\n",getc(fp),ftell(fp));
        n=n+5L;
 }
 putchar('\n');
 fseek(fp,-1L,2);/*position to the last character*/
 do
 {
        putchar(getc(fp));
 }
 while(!fseek(fp,-2L,1));
 fclose(fp);
 getch();
}


fflush () :- In the C Programming Language, the fflush function writes any unwritten data
in stream's buffer. If stream is a null pointer, the fflush function will flush all streams with unwritten
data in the buffer.


Syntax
int fflush(FILE *stream);
 stream:- The stream to flush.

Example:-
#include <stdio.h>
#include <stdlib.h>
int main()
{
     char ans[8];
      int i;
for(i=1;i<=3;i++)
 {
        printf("\n What is the unit of traffic ?");
        scanf("%s",ans);
     fflush(stdin);
      if(stricmp(ans,"Earlang")==0)
     {
            printf("\nAnswer is correct");
            exit(1);
     }
    else
     if(i<3)
       printf("\n Try Again!\n");
 }
 printf("\n Nunit of traffic is Earlang:");
}

Post a Comment

0 Comments