繁体   English   中英

如何将两个文本文件读入两个动态分配的数组并在c中逐字节比较它们?

[英]How to read two text files into two dynamically allocated arrays and compare them byte by byte in c?

我想编写一个程序,比较两个文本文件,并将文件二中与文件一不同的每个字节写入第三文件。 问题是必须将文本文件读取到动态分配的数组中。 逐字节比较数组,文件2的数组中与文件1的数组不同的任何字节将放入第三个数组。 然后将该数组复制到一个新的文本文件中。 这将如何实现?

基本上,以下代码如何使用动态分配的数组获得相同的结果?

#include <stdio.h>
int main(int argc, char *argv[])
{
    int offset;
    int ch1, ch2;
    FILE *fh1, *fh2, *fh3=stdout;
    if( argc<3 ) {
        printf("need two file names\n"); return(1);
    }
    if(!(fh1 = fopen(argv[1], "r"))) {
        printf("cannot open %s\n",argv[1]); return(2);
    }
    if(!(fh2 = fopen(argv[2], "r"))) {
        printf("cannot open %s\n",argv[2]); return(3);
    }
    if(argc>3) {
        if(!(fh3 = fopen(argv[3], "w+"))) {
            printf("cannot open %s\n",argv[3]); return(4);
        }
    }
    for(offset = 0; (!feof(fh1)) && (!feof(fh2)); offset++)
    {
        ch1=ch2='-';
        if(!feof(fh1)) ch1 = getc(fh1);
        if(!feof(fh2)) ch2 = getc(fh2);
        if(ch1 != ch2)
            fprintf(fh3,"%d:%c %c\n", offset, ch1, ch2);
        else
            fprintf(fh3,"%c\n", ch1);
    }
    return 0;
}

简单的方法可能是使用fseek()+ ftell()来确定文件的大小,然后分配空间。 另一种方法可以是

size_t pos = 0;
size_t allocated = 1024;  /* arbitrary value */
void *tmp = malloc(allocated);
BUG_ON(!tmp)
while (!feof(f)) {
    size_t l = fread(tmp + pos, 1, allocated - pos, f);
    pos += l;
    allocated += l + 1024;    /* arbitrary value */
    tmp = realloc(tmp, allocated);
    BUG_ON(!tmp);
}

tmp = realloc(tmp, pos);  /* free unneeded space */

当您使用Linux / POSIX时,可以映射文件并直接访问内存。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM