C 语言中的“差异”Linux 实用程序实现

问题描述

我们的 CS 教授给我们分配了通过编写 C 程序来实现 diff LINUX 命令的作业。

我首先提取了在两个不同数组(line1 和 line2)中作为命令行参数传递的两个文件的行。

那之后怎么办?如何报告诸如 1,3c2,4 之类的更改; 1d0;等

输入将是这样的:

./diff file1.txt file2.txt

(其中,diff 是我需要编写的 C 代码的编译文件名)

阅读这里的差异输出https://www.howtoforge.com/tutorial/linux-diff-command-file-comparison/

(或者,如果您有 LINUX,请尝试在那里使用它以查看输出

我只需要实现这部分,不需要为-c等额外功能编写额外的代码

我已经写了这个:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define LSIZ 200 
#define RSIZ 100

// diff Implementation
int main(int argc,char **argv){

    if(argc == 1){printf("No file names given!\n"); exit(1);}         
    if(argc > 3){printf("Cannot have more than 2 file names!\n"); exit(1);}
    
    // FILE 1    
    char line1[RSIZ][LSIZ];
    
    FILE *f1 = fopen(argv[1],"r");
    if(f1==0){ perror("Error opening the File!\n"); exit(1); } 

    int i1 = 0;
    int tot1 = 0;
    while(fgets(line1[i1],LSIZ,f1)){
        line1[i1][strlen(line1[i1]) - 1] = '\0';
        i1++;
    }
    tot1 = i1;   

    fclose(f1);

    // FILE 2    
    char line2[RSIZ][LSIZ];
    
    FILE *f2 = fopen(argv[2],"r");
    if(f2==0){ perror("Error opening the File!\n"); exit(1); } 

    int i2 = 0;
    int tot2 = 0;
    while(fgets(line2[i2],f2)){
        line2[i2][strlen(line2[i2]) - 1] = '\0';
        i2++;
    }
    tot2 = i2;

    fclose(f2);    

}


解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)