Feb 7, 2012

K & R C Programs Exercise 7-6.

K and R C, Solution to Exercise 7-6:
K and R C Programs Exercises provides the solution to all the exercises in the C Programming Language (2nd Edition). You can learn and solve K&R C Programs Exercise.
Write a C Program to compare two files, printing the first line where they differ.
Read more about C Programming Language .

/***********************************************************
* You can use all the programs on  www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact info@c-program-example.com
* To find more C programs, do visit www.c-program-example.com
* and browse!
* 
*                      Happy Coding
***********************************************************/

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

#define MAXLINE 100
/*comp: compare two file, printing the first line where they differ*/
main(int argc, char *argv[])
{
 FILE *fp1, *fp2;
 void filecomp(FILE *fp1, FILE *fp2);
 if(argc != 3){
  fprintf(stderr,"comp:need two file names\n");
  exit(1);
 } else {
  if((fp1 = fopen(*++argv, "r")) == NULL) {
   fprintf(stderr, "comp:can't open %s\n",*argv);
   exit(1);
  } else if((fp2 = fopen(*++argv, "r")) == NULL) {
   fprintf(stderr, "comp:can't open %s\n",*argv);
   exit(1);
  }else  {
   filecomp(fp1,fp2);
   fclose(fp1);
   fclose(fp2);
   exit(0);

  }
 }
}

//filecomp: compare two files -a line at a time
void filecomp (FILE *fp1, FILE *fp2)
{
 char line1[MAXLINE], line2[MAXLINE];
 char *lp1 = *lp2;
 do{
  lp1 = fgets(line1, MAXLINE, fp1);
  lp2 = fgets(line2, MAXLINE, fp2);
  if(lp1 == line1 && lp2 == line2){

   if(strcmp(line1,line2) !=0) {
    printf("First difference in line\n%s\n",line1);
    lp1 = lp2 = NULL;
   }
  } else if(lp1 != line1 && lp2 == line2)
   printf("end of first file at line\n%s\n",line2);
  else if(lp1 == line1 && lp2 == line2)
   printf("end of second file at line \n%s\n",line1);

 }while(lp1 == line1 && lp2 == line2);
}



Read more c programs

C Basic
C File i/o
K and R C Programs Exercise
You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it


(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!

To browse more C Programs visit this link