c - 如何在 C 中将两个文本文件中的差异写入另一个文本文件?

标签 c file text io difference

我想编写一个程序来比较两个文件,并将文件一中与文件二不同的每个字节写入第三个文件。我想逐字节比较文件并将任何不同的单个字节写入第三个文件。我对文件 I/O 不是很熟悉。谁能给我一个完成此任务的示例程序?

这是我目前所拥有的:

int main(int argc, char *argv[]) {
  int file1, file2, file1size, file2size;
  // int  difference1, difference2;
  char buf;

  if (argc != 3){
    fprintf(stderr, "Usage %s <file1> <file2>", argv[0]);
    exit(1);
  }
  if ((file1 = open(argv[1], 0400)) < 0) { //read permission for user on file source
    fprintf(stderr, "Can't open source");
    exit(1);
  }
  if ((file2 = open(argv[2], 0400)) < 0) { //read permission for user on file source
    fprintf(stderr, "Can't open source");
    exit(1);
  }
  file1size = lseek(file1, (off_t) 0, SEEK_END);
  printf("File 1's size is %d\n", file1size);
  file2size = lseek(file2, (off_t) 0, SEEK_END);
  printf("File 2's size is %d\n", file2size);



}

我不确定如何比较 file1 和 file2 的字节,然后将差异写入另一个文件。

最佳答案

这与您要找的很接近。

#include <stdio.h>

int main(int argc, char *argv[]) {
    FILE *file1 = fopen(argv[1], "r");
    FILE *file2 = fopen(argv[2], "r");
    int i;
    for(i = 0; !feof(file1) || !feof(file2); i++) {
        int byte1 = getc(file1);
        int byte2 = getc(file2);
        if(byte1 != byte2) {
            printf("%d %d %d\n", i, byte1, byte2);
        }
    }
    return 0;
}

它将这两个文件作为命令行参数并逐字节比较这两个文件。如果两个字节不同,则打印字符 #,以及这两个字符的 ASCII 值。 -1 表示已经达到 EOF。

您必须(理解并)使其适应您想要的输出格式。 (我假设这是家庭作业。)

feof 测试文件结尾。

getc 从文件中获取下一个字符(字节)。如果已到达文件末尾,则为 -1。

而且您似乎已经知道 printf 的作用。

关于c - 如何在 C 中将两个文本文件中的差异写入另一个文本文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19648137/

相关文章:

excel - Excel 数据连接的相对文件路径

html - 将文本输入框对齐到 div 的右侧

c - 如何获取C语言执行shell命令的响应结果?

c - 分配从指针目标类型中丢弃 ‘const’ 限定符 - 尝试检索值时

c - voronoi 图不正确

file - 在 Go 中读取/写入文件的正确方法

Android:我可以将单个 InputStream 用于多种方法吗?

c - arduino 上的脉冲生成和读出

Python - 查找文本文件中单词列表的单词频率

java - 如何打印像表格这样的二维数组