Monday, August 11, 2014

C PROGRAMS FOR FILE HANDLING


C - programs for file handling. Some examples.

1.      Write a program to display contents of a file on screen

#include <stdio.h>
#include <conio.h>
int main()
{
     FILE *fp;
     int c ;

     fp = fopen( "input.txt", "r" );   /* input.txt is file name to open*/
     c = getc( fp ) ;          
     while (  c != EOF )
     {
           putchar( c );       
           c = getc ( fp );      
     }

     fclose( fp );
     getch();
     return 0;
}
2.      Write a program to promt user to input filename and read the content of file and display.

#include <stdio.h>
#include <stdio.h>
#include <conio.h>
 main()
{

   FILE  *fp;
   int c ;
   char filename[40] ;
   printf("Enter file to be displayed: ");
   gets( filename ) ;
   fp = fopen( filename, "r"); 
   c = getc( fp ) ;            

   while (  c != EOF )
   {
        putchar(c);         
        c = getc ( fp );    
   }
   fclose( fp );
    getch();
    return 0;
}



3.      Write a ‘C’ program to read a text file and print the text in reverse order.

#include<stdio.h>
#include<stdlib.h>
void main()
{
FILE *fp;
char ch;
int i,pos;
clrscr();
fp=fopen("input.txt","r+");
fseek(fp,1,SEEK_END);
pos=ftell(fp);
i=0;
while(i<=pos)
{
ch=fgetc(fp);
printf("%c",ch);
fseek(fp,-i,SEEK_END);
i++;
}
getch();
}

4.      Write a program to count the number of lines and characters in a file.
Note: Each line of input from a file or keyboard will be terminated by the newline character ‘\n’.
Thus by counting newlines we know how many lines there are in our input.

#include <stdio.h>
#include <conio.h>
 main()
{

   FILE  *fp;
   int c , nc, nlines;
   char filename[40] ;
   nlines = 1 ;
   nc = 0;
   printf("Enter file name: ");
   gets( filename );
   fp = fopen( filename, "r" );    
   if ( fp == NULL )
   {
        printf("Cannot open %s for reading \n", filename );
        exit(1);      /* terminate program */
   }
   c = getc( fp ) ;            
   while (  c != EOF )
   {
        if ( c  ==  '\n'  )   
             nlines++ ;
        nc++ ; 
        c = getc ( fp );
   }
   fclose( fp );
   if ( nc != 0 )
   {
        printf("There are %d characters in %s \n", nc, filename );
        printf("There are %d lines \n", nlines );
   }
   else
        printf("File: %s is empty \n", filename );
   getch();
   return 0;
}

5.      Write a progra to compare the two file whether they are identical or not.

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
 main()
{
    FILE *fp1, *fp2;
     int ca, cb;
     char fname1[40], fname2[40] ;

     printf("Enter first filename:") ;
     gets(fname1);
     printf("Enter second filename:");
     gets(fname2);
     fp1 = fopen( fname1,  "r" );       /* open for reading */
     fp2 = fopen( fname2,  "r" ) ;      /* open for writing */ 
     if ( fp1 == NULL )      /* check does file exist etc */
     {
           printf("Cannot open %s for reading \n", fname1 );
           getch();
           exit(1);    /* terminate program */
     }
     else if ( fp2 == NULL )
     {
           printf("Cannot open %s for reading \n", fname2 );
           getch();
           exit(1);    /* terminate program */
     }
     else       /* both files opened successfully  */
     {
           ca  =  getc( fp1 ) ;      
           cb  =  getc( fp2 ) ;

           while ( ca != EOF&&cb != EOF&&ca == cb)
           {
                ca  =  getc( fp1 ) ;     
                cb  =  getc( fp2 ) ;
           }
           if (  ca == cb )
                printf("Files are identical \n");
           else if ( ca !=cb )
                printf("Files differ \n" );
           fclose ( fp1 );           
           fclose ( fp2 );
     }
     getch();
     return 0;
}

6.      Write a program to read a text file and copy all contents in the new file.
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
 main()
{
    FILE *fp1, *fp;
     int c ;

     fp1 = fopen( "input.txt",  "r" );       /* open for reading */
     fp2 = fopen( "input.new", "w" ) ; /* open for writing */  

     if ( fp1 == NULL )      /* check does file exist etc */
     {
           printf("Cannot open input.txt for reading \n" );
           getch();
           exit(1);    /* terminate program */
     }
     else if ( fp2 == NULL )
     {
           printf("Cannot open input.new for writing \n");
        getch();
           exit(1);    /* terminate program */
     }
     else       /* both files O.K. */
     {
           c = getc(fp1) ;     
           while ( c != EOF)
           {
                putc( c,  fp2);    /* copy to input.new */
                c =  getc( fp1 ) ;
           }

     fclose ( fp1 );            /* Now close files */
     fclose ( fp2 );
     printf("Files successfully copied \n");
     }
     getch();
     return 0;
}



7.      Write a program to open a new file, read rollno, name, address and phone_no until the user says "no" . After reading all the data, write it to the file. Display the records from file in alphabetical order of student name.

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>
#define MAX 100

typedef struct student
{
     int rollNo;
     char name[40];
     char address[50];
     char phoneNo[20];
}student;

main()
{
     int i=0,j,n;
     char choice[5];
     student stu[MAX],tmp,s[MAX];
     FILE *fp;
     fp=fopen("records.dat","w+");
     if(fp==NULL)
     {
          printf("\nError creating file!");
          getch();
          exit(1);
     }

     do{
          printf("Enter the record of student %d\n",i+1);
          printf("RollNo:");
          scanf("%d",&stu[i].rollNo);
          printf("Name:");
          scanf("%s",stu[i].name);
          printf("Address:");
          scanf("%s",stu[i].address);
          printf("Phone NO:");
          scanf("%s",stu[i].phoneNo);
          i++;
          printf("\nDo you want to add another record?(yes/no)");
          scanf("%s",choice);
                   /*if(strcmp(choice,"no"==0))
                        break;*/
     }while(strcmp(choice,"no")!=0);

     fwrite(&stu[0],sizeof(student),i,fp);
     rewind(fp);
     n=0;
     while(1)
     {
          if(fread(&s[n],sizeof(student),1,fp)==0)
              break;
          n++;
     }

     for(i=0;i<n-1;i++)
          for(j=i+1;j<n;j++)
              if(strcmp(s[i].name,s[j].name)>0)
              {
                   tmp=s[i];
                   s[i]=s[j];
                   s[j]=tmp;
              }
     //printf("\nRecords of students :");
    
printf("\n\nRecord of students after sorting alphabetically");
     for(i=0;i<n;i++)
     {
          printf("\n\nRecord of Student %d\n",i+1);
          printf("\n Roll No: %d",s[i].rollNo);
          printf("\nName: %s",s[i].name);
          printf("\nAddress:%s",s[i].address);
          printf("\nPhone No: %s",s[i].phoneNo);
     }
     fclose(fp);
     getch();
     return 0;
}



8.     Write a program to read a text file and replace the each occurrence of the word  input by the user with the next word input by the user.

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>
#define MAX 100

main()
{
     int i,n;
     char find[MAX],rep[MAX],tmp[MAX];
     char c;
     FILE *fp,*fp1;
     fp=fopen("input.txt","r");
     fp1=fopen("input1.txt","w");
    
     if(fp==NULL)
     {
          printf("\nFile not found !");
          getch();
          exit(1);
     }
    
     if(fp1==NULL)
     {
          printf("\nError creating file!");
          getch();
          exit(1);
     }
     printf("Enter what string to find:");
     scanf("%s",find);
     printf("\nEnter the string to replace with:");
     scanf("%s",rep);
     i=0;n=0;
     while((c=getc(fp))!=EOF)
     {
     if(c==' '||c=='\n'||c==’,’||c==’.’)
     {
       tmp[i]='\0';
       i=0;
       printf("\ncomplete word=%s",tmp);
    
       if(strcmp(find,tmp)==0)
       {
        fprintf(fp1,"%s",rep);
        fputc(c,fp1);
        n++;
        i=0;
       }
       else
       {
         fprintf(fp1,"%s",tmp);
         fputc(c,fp1);
         i=0;
       }
     }
else
{
    tmp[i]=c;
    i++;
}
}/*end while*/

if(c==EOF)
     {
       tmp[i++]='\0';
       i=0;
      
       if(strcmp(find,tmp)==0)
       {
        fprintf(fp1,"%s",rep);
        n++;
        i=0;
       }
       else
       {
         fprintf(fp1,"%s",tmp);
         i=0;
       }
     }
printf("\n%d replaceent",n);
fclose(fp);
fclose(fp1);
remove("input.txt");
rename("input1.txt","input.txt");
getch();
return 0;
}

9.     Write a program to print the arguments at command line using command line arguments.
#include <stdio.h>
#include <stdlib.h>

int main(int argc,  char *argv[])
{
   int i = 0 ;
   int num_args ;

   num_args = argc ;

   while( num_args > 0)
   {
        printf(“%s\n“, argv[i]);
        i++ ;
        num_args--;
   }
}

10.  Write a program that reads a text file and creates another text file and writes  into new file by replacing the words of first file as “Ram” with “Hari”, “Sita” with “Gita” and “Govinda” with “Shiva”.

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>
#define MAX 100

main()
{
     int i,n;
     char *s1="Ram",*s2="Sita",*s3="Govinda";
    char *r1="Hari",*r2="Gita",*r3="Shiva";
    char tmp[MAX];
     char c;
     FILE *fp,*fp1;
     fp=fopen("input.txt","r");
     fp1=fopen("input1.txt","w");
    
     if(fp==NULL)
     {
          printf("\nFile not found !");
          getch();
          exit(1);
     }
    
     if(fp1==NULL)
     {
          printf("\nError creating file!");
          getch();
          exit(1);
     }
     i=0;n=0;
     while((c=getc(fp))!=EOF)
     {
     if(c!=' '&&c!='\n'&&c!=','&&c!='.')
     {
      tmp[i]=c;
      i++;
      }
      else
      {
       tmp[i]='\0';
       i=0;
       printf("\ncomplete word=%s",tmp);
    
       if(strcmp(s1,tmp)==0)
       {
        fprintf(fp1,"%s",r1);
        fputc(c,fp1);
        i=0; n++;
       }
       else if(strcmp(s2,tmp)==0)
       {
        fprintf(fp1,"%s",r2);
        fputc(c,fp1); n++;
        i=0;
       }
       else if(strcmp(s3,tmp)==0)
       {
        fprintf(fp1,"%s",r3);
        fputc(c,fp1);
        n++;
        i=0;
       }
       else
       {
         fprintf(fp1,"%s",tmp);
         fputc(c,fp1);
         i=0;
       }
     }

}/*end while*/

printf("\n%d replaceent",n);
fclose(fp);
fclose(fp1);
getch();
return 0;
}

11.  Write a program that reads a text file and deletes each occurrence of the word “Ram”.

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>
#define MAX 100

main()
{
     int i,n;
     char *s1="Ram";
    char tmp[MAX];
     char c;
     FILE *fp,*fp1;
     fp=fopen("input.txt","r");
     fp1=fopen("input1.txt","w");
     if(fp==NULL)
     {
          printf("\nFile not found !");
          getch();
          exit(1);
     }
     if(fp1==NULL)
     {
          printf("\nFile not Created !");
          getch();
          exit(1);
     }
     i=0;n=0;
     while((c=getc(fp))!=EOF)
     {
     if(c!=' '&&c!='\n'&&c!=','&&c!='.')
     {
      tmp[i]=c;
      i++;
      }
      else
      {
       tmp[i]='\0';
       i=0;
       printf("\ncomplete word=%s",tmp);
    
       if(strcmp(s1,tmp)==0)
       {
        fputc(c,fp1);
        i=0; n++;
       }
       else
       {
         fprintf(fp1,"%s",tmp);
         fputc(c,fp1);
         i=0;
       }
     }

}/*end while*/

printf("\nTotal %d word deleted.",n);
fclose(fp);
fclose(fp1);
remove("input.txt");
rename("input1.txt","input.txt");
getch();
return 0;
}


HackerBoy

Compiled By Sabin Khanal

0 comments:

Post a Comment

 

Copyright @ 2013 Learn Programming.

Designed by Templateiy & CollegeTalks