john pfeiffer
  • Home
  • Categories
  • Tags
  • Archives

file compare text

/* John Pfeiffer, 25dec07 */
/* a simple text file comparison by character - 
counts chars & lines, will display where first non-match is */

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

#define CMDLINE_PARAMETERS 3
void program_usage_help( char* argv[] );

void test_commandline_parameters( int argc, char* argv[] );

int main(int argc, char* argv[])
{
    char c1, c2;
    int chars=0, lines=1, exact_match = 1;   
    FILE* fp1;
    FILE* fp2;
    test_commandline_parameters( argc, argv );
    fp1 = fopen(argv[1],"r");
    fp2 = fopen(argv[2],"r");

    if( fp1 == NULL || fp2 == NULL )
    {    printf("error opening file\n");}
    else
    {
        do{     
            c1 = getc(fp1);
            c2 = getc(fp2);
            if( c1 == '\n' )
            {   lines++;    }

            if( c1 != c2 )
            {   exact_match = 0;    
                break;
            }
            else if( (c1 == EOF && c2 != EOF) || (c1 != EOF && c2 == EOF) )
            {   exact_match = 0;  
                break;
            }
            chars++;           
        }while( (c1 != EOF) && (c2 != EOF) );

        fclose(fp1);
        fclose(fp2);
    }

    printf("There were %d chars, %d lines.\n", chars, lines);
    printf("Exact Match: %d (0=false,1=true)", exact_match);

    return 0;
}

void program_usage_help( char* argv[] )
{   printf("%s filename1.txt filename2.txt",argv[0]); 
}/* end program_usage_help */

void test_commandline_parameters( int argc, char* argv[] )
{   int i = 0;
    if( argc < CMDLINE_PARAMETERS )
    {   printf("\nMore parameters needed, e.g.\n"); 
        program_usage_help( argv );
        exit(1);
    }
    else if( argc > CMDLINE_PARAMETERS )
    {   printf("\nToo many command line parameters, e.g.\n");   
        program_usage_help( argv );
        exit(1);
    }
    else
    {   while( i < argc )
        {   printf("%s ", argv[i]);     
            i++;
        }
        printf("in progress...\n\n");
    }

}/* end test_commandline_paramters func */

  • « cmd dos basics video card debug
  • Linux story dec07 lilo »

Published

Dec 25, 2007

Category

c

~174 words

Tags

  • c 95
  • compare 4
  • file 92
  • text 16