A C program compares 2 files and find its first difference if they are different

This C program will compare two files and find the first line of difference if there is a difference. This is just a basic example of how to read files using C programming, in unix like systems, there is already a command line tool (diff) you can use to compare two files.

    To compile the program: gcc diff.c
    To run the program: ./a.out file1.txt file2.txt

int main(int argc, char *argv[]){
  FILE *fp1, *fp2;
  int nl;
  char r, r2;
  int identical;
  //fp1 = fopen(file1, "r");/* open file1 and file2 for reading */
  //fp2 = fopen(file2, "r");
  /* if either of these file does not exist, print error and return */
  if((fp1 = fopen(argv[1], "r")) == NULL){
    printf("Error -- Cannot open file: %s\n\n", argv[1]);
  if((fp2 = fopen(argv[2], "r")) == NULL){
    printf("Error -- Cannot open file: %s\n\n", argv[2]);
  nl=1;/* Set the number line equals to 1 first.*/
  while(!feof(fp1)) {
    r = fgetc(fp1);/*use r to read each character from file1, use r2 to read each character from file2. */             
    r2 = fgetc(fp2);      
    if(r =='\n')/* if the character read if a new line, increment nl by 1*/
    if(r != r2){/* if r is not equal to r2, we have find the difference, print the following message */                          
      printf("The files are different; the first difference is in line %d.\n\n", nl); 
      identical = 0;     
    printf("The files are identical.\n\n");
  if((fclose( fp1 ) == EOF)||(fclose( fp2 ) == EOF)) {/* close the file */
    printf("Error closing first file.\n\n");

Search within Codexpedia

Custom Search

Search the entire web

Custom Search