Exercise 7-6 (diff - Compare files)

Chapter_7     Exercise_7-5     cat_(concatenate) Exercise_7-7







Exercise 7-6     K&R, p. 165


Exercise 7-6. Write a program to compare two files, printing the first line where they differ.




Note:  See also ch7-cat_(concatenate).




diff2.c     K&R, p. 165         download


#include <stdio.h> // for fprintf(), fopen(), fclose(), ferror(),
// getc(), putc(), stdin, stdout, stderr, FILE, EOF, NULL
#include <string.h> // for strlen(), strcmp()
#include <stdlib.h> // for exit()

#define MAXLINE 1000

// get at most n-1 chars from fp:
char * fGets(char *s, int n, FILE *fp); // fgets() is in stdio.h
// write string line on stdout:
int writeLine(char *line);

int main(int argc, char *argv[])
{
if (argc != 3)
{
fprintf(stderr, "Usage: %s file1 file2\n", argv[0]);
exit(1); // end program, signalling error
}

FILE *fp1, *fp2;
fp1 = fopen(argv[1], "r");
fp2 = fopen(argv[2], "r");

if (fp1 == NULL || fp2 == NULL)
{
fprintf(stderr, "%s: can't open \"%s\" or \"%s\"\n",
argv[0], argv[1], argv[2]);
exit(1); // end program, signalling error
}

char line1[MAXLINE], line2[MAXLINE];
int lineno = 0;

while (fGets(line1, MAXLINE, fp1) != NULL &&
fGets(line2, MAXLINE, fp2) != NULL)
{
lineno++;
if (strcmp(line1, line2)) // not 0
{
fprintf(stderr, "%s: line %d:\n", argv[0], lineno);
fprintf(stderr, "%s: %s", argv[1], line1);
// writeLine(line1);
fprintf(stderr, "%s: %s", argv[2], line2);
// writeLine(line2);
break; // exit(0);
}
}
fclose(fp1), fclose(fp2);

exit(0);
}

// get at most n-1 chars from fp:
char * fGets(char *s, int n, FILE *fp) // fgets() is in stdio.h
{
register int c;
register char *cs;

cs = s;
while (--n > 0 && (c = getc(fp)) != EOF)
{
if ((*cs++ = c) == '\n')
{break;}
}
*cs = '\0';

return (c == EOF && cs == s) ? NULL : s;
}
// read a line, return length:
int getLine(char *line, int max) // getline() is in stdio.h
{
if (fGets(line, max, stdin) == NULL)
{return 0;}
// else
return strlen(line); // sizeof(line)
}

// put string s on file fp:
int fPuts(char *s, FILE *fp) // fputs() is in stdio.h
{
int c;

while (c = *s++)
{putc(c, fp);}

return ferror(fp) ? EOF : 0;
}
int writeLine(char *line)
{
return fPuts(line, stdout);
}
/*
gcc diff2.c -o diff2
./diff2
Usage: ./diff2 file1 file2

./diff2 cat.c cat1.c
./diff2: can't open "cat.c" or "cat1.c"

diff cat1.c cat1.c
./diff2 cat1.c cat1.c
// no output (files are identical)

./diff2 cat1.c cat2.c
./diff2: line 1:
cat1.c: #include <stdio.h> // for printf(), fopen(), fclose(), stdin, stdout,
cat2.c: #include <stdio.h> // for fprintf(), fopen(), fclose(), ferror(),

diff cat1.c cat2.c
*/









Chapter_7     Exercise_7-5     cat_(concatenate) BACK_TO_TOP Exercise_7-7



Comments

Popular posts from this blog

Contents

Blogger Page Margins in Contempo