c语言7-6 大赛选手排名,c程序设计语言_习题7-6_对比两个输入文本文件_输出它们不同的第一行_并且要记录行号...

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

Here's Rick's solution:

/******************************************************

KnR 7-6

--------

Write a program to compare two files and print the

first line where they differ.

Author: Rick Dearman

email: rick@ricken.demon.co.uk

Note: This program prints ALL the lines that are

different using the <> indicators used by

the unix diff command. However this program

will not cope with something as simple as a

line being removed.

In reality the program would be more useful

if it searched forward for matching lines.

This would be a better indicator of the simple

removal of some lines.

This has lead me to track down a version of the

"diff" command available on GNU/Linux systems.

for more information go to the web site at:

www.gnu.org

******************************************************/

#include #include

#define MAXLINE 1000

void diff_line( char *lineone, char *linetwo, intlinenumber )

{if(strcmp (lineone, linetwo) < 0 || strcmp (lineone, linetwo) > 0)

printf("%d

%d>%s", linenumber, lineone, linenumber, linetwo);

}int main(int argc, char *argv[] )

{

FILE*fp1, *fp2;charfp1_line[MAXLINE], fp2_line[MAXLINE];inti;if ( argc != 3)

{

printf("differ fileone filetwo");

exit(0);

}

fp1= fopen( argv[1], "r");if ( !fp1 )

{

printf("Error opening file %s", argv[1]);

}

fp2= fopen( argv[2], "r");if ( !fp2 )

{

printf("Error opening file %s", argv[2]);

}

i= 0;while ( (fgets(fp1_line, MAXLINE, fp1) !=NULL)&& (fgets(fp2_line, MAXLINE, fp2) !=NULL))

{

diff_line( fp1_line, fp2_line, i );

i++;

}return 0;

}

and here's "flippant squirrel"'s solution:

/* Exercise 7-6 - write a program to compare two files, printing the first line

* where they differ

*

* Note : I amended this a bit...if a file is shorter than the other, but is identical

* up to that point, the program prints out "EOF" as the string that's not equal.

*

*/

#include #include#include

#define BUFF_SIZE 1000

/*uses fgets, removes the '

' at the end of the string if it exists*/

char *safegets(char *buffer, int length, FILE *file)

{char *ptr;intlen;if (buffer !=NULL)

{

ptr=fgets(buffer, length, file);if (ptr !=NULL)

{

len=strlen(buffer);if (len > 0)

{if (buffer[len - 1] == '')

{

buffer[len- 1] = '

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值