linux两个文件匹配,如何查找两个文本文件之间的匹配模式以及输出到另一个文件?_linux_开发99编程知识库...

實際上我試圖解決我認為你在設計的"難題"。 下面的代碼查找在file1和file2中找到的最長字元串。 如果有多個"最長"字元串,則只報告找到的第一個字元串。 可能會對某人有所幫助,在某些情況下,( 雖然你在這裡找的解決方案可能不是):#include

#include

#include

#include

#include

/* This routine returns the size of the file it is called with. */

static unsigned

get_file_size (const char * file_name)

{

struct stat sb;

if (stat (file_name, & sb)!= 0) {

fprintf (stderr,"'stat' failed for '%s': %s.n",

file_name, strerror (errno));

exit (EXIT_FAILURE);

}

return sb.st_size;

}

/* This routine reads the entire file into memory. */

static unsigned char *

read_whole_file (const char * file_name)

{

unsigned s;

unsigned char * contents;

FILE * f;

size_t bytes_read;

int status;

s = get_file_size (file_name);

contents = malloc (s + 1);

if (! contents) {

fprintf (stderr,"Not enough memory.n");

exit (EXIT_FAILURE);

}

f = fopen (file_name,"r");

if (! f) {

fprintf (stderr,"Could not open '%s': %s.n", file_name,

strerror (errno));

exit (EXIT_FAILURE);

}

bytes_read = fread (contents, sizeof (unsigned char), s, f);

if (bytes_read!= s) {

fprintf (stderr,"Short read of '%s': expected %d bytes"

"but got %d: %s.n", file_name, s, bytes_read,

strerror (errno));

exit (EXIT_FAILURE);

}

status = fclose (f);

if (status!= 0) {

fprintf (stderr,"Error closing '%s': %s.n", file_name,

strerror (errno));

exit (EXIT_FAILURE);

}

return contents;

}

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

int i1, i2, l1, l2, lm;

unsigned char longestString[1000];//lazy way to make big enough.

unsigned char tempString[1000];

int longestFound=0;

unsigned char *f1, *f2;//buffers with entire file contents

f1 = read_whole_file (argv[1]);

f2 = read_whole_file (argv[2]);

l1 = strlen(f1);

l2 = strlen(f2);

for(i1 = 0; i1

lm = 0;//length of match

for(i2 = i1; i2

lm = 0;

while (f1[i1+lm] == f2[i2+lm] && (i1+lm

tempString[lm] = f1[i1+lm];

lm++;

}

if (lm> longestFound) {

tempString[lm]=0;//terminate string

strcpy(longestString, tempString);

longestFound = lm;

}

}

}

printf("longest string found is %d characters:n", longestFound);

printf("%sn", longestString);

free(f1);

free(f2);

return 0;

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值