Lab Exercises

  1. Write a program to compare two files, printing the first line where they differ.
  2. Write a program that, given two files exam1.dat and exam2.dat, appends the second file to the first.
  3. Write a program that displays the contents of a file in reverse order.

Lab Solutions

  1. Program that compares two files -
     #include <stdio.h>
    #include <string.h>
    void main()
    {
        char str1[251],str2[251];
        FILE *fp1, *fp2; 
        /* assume that two files, exam1.dat and exam2.dat exist already */
        fp1=fopen ("exam1.dat", "r"); 
        fp2=fopen ("exam2.dat", " r");
        while (fgets (str1,251, fp1) ! =NULL)
        {
            if (fgets (str2,251, fp2) ==NULL)
            {
                printf ("
    Exam1 is longer"); 
            break;
         }
         if (strcmp (strl, str2) !=0)
         {
             printf("
    The lines where they differ are");
             print f ("%s", str1); 
             printf ("%s", str2); 
             break;
          }
       }
       if (strcmp (strl, str2) ==0 && fgets (str2, 251, fp2)! =NULL)
       {
          print f ("
    Exam2 is longer"):	
          return;
        }
        if (strcmp (strl, str2) ==0) 
            printf ("
    The two files are equal");
        fclose (fp1) ;
        fclose ( fp2) ;
    }
    
  2. Program that appends one file to another -
    #include <stdio.h> 
    void main()
    {
        char c;
        FILE *fp1, *fp2;
        /* assume that two files, exam1.dat and exam2.dat exist already */
        fp1 = fopen ("exam1.dat", "a");
        fp2 = fopen ("exam2.dat", "r");
        c=fgetc (fp2);
        while(c != EOF)
        {
           fputc (c, fp1);
           c=fgetc(fp2);
         }
         fclose (fp1); 
         fclose (fp2);
    }
    
    
  3. Program that displays the contents of a file in reverse order -
    #include <stdio.h> 
    void main ()
    {
       char c; 
       long int pos;
       FILE *fp; 
       /* assume that a file, exam.dat exists already */ 
       fp = fopen ( "exam.dat", "r"); 
       pos = ftell (fp); 
       fseek ( fp, -1,2) ;
       while (ftell (fp) >pos) 
       {
          c=fgetc (fp); 
          fseek (fp, -2, 1) ; 
          printf ("%c", c); 
       }
       c=fgetc(fp);
       printf("%c", c); 
       fclose (fp) ;
    }