从命令行读取两个文件并比较两个文件的大小

时间:2016-07-19 09:02:45

标签: c file file-processing

我正在创建一个c程序,从命令行中读取参数中的两个文件,并比较两个文件的大小 这是我编码的内容

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

int main (int argc, char *argv[]){
FILE *file1, *file2;
int char1, char2;
char fname1 = argv[1];
char fname2 = argv[2];
file1 = fopen(fname1, "r");
file2 = fopen(fname2, "r");

if (file1 == NULL){
    printf("Cannot open %s\n", fname1);
    exit(1);
} else if (file2 == NULL) {
    printf("Cannot open %s for reading\n", fname2);
    exit(1);
}else{
    char1 = getc(file1);
    char2 = getc(file2);

    while((char1 != EOF) && (char2 != EOF) && (char1 == char2)) {
        char1 = getc(file1);
        char2 = getc(file2);
    }

    if (char1 == char2)
        printf("Files are the same\n");
    else if (char1 > char2){
        printf("%s is larger\n", file1);
    } else if(char1 < char2){
        printf("%s is larger\n", file2);
    }
    fclose(file1);
    fclose(file2);
}
return (0);

}

然而,终端返回了很多错误信息。

test.c: In function ‘main’:
test.c:7:19: warning: initialization makes integer from pointer without a cast [enabled by default]
     char fname1 = argv[1];
               ^
test.c:8:19: warning: initialization makes integer from pointer without a cast [enabled by default]
     char fname2 = argv[2];
               ^
test.c:9:5: warning: passing argument 1 of ‘fopen’ makes pointer from integer without a cast [enabled by default]
     file1 = fopen(fname1, "r");
     ^
In file included from test.c:1:0:
/usr/include/stdio.h:272:14: note: expected ‘const char * __restrict__’ but argument is of type ‘char’
 extern FILE *fopen (const char *__restrict __filename,
              ^
test.c:10:5: warning: passing argument 1 of ‘fopen’ makes pointer from integer without a cast [enabled by default]
     file2 = fopen(fname2, "r");
     ^
In file included from test.c:1:0:
/usr/include/stdio.h:272:14: note: expected ‘const char * __restrict__’ but argument is of type ‘char’
 extern FILE *fopen (const char *__restrict __filename,
              ^
test.c:13:9: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘int’ [-Wformat=]
         printf("Cannot open %s\n", fname1);
         ^
test.c:16:9: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘int’ [-Wformat=]
         printf("Cannot open %s for reading\n", fname2);
         ^
test.c:30:13: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘struct FILE *’ [-Wformat=]
             printf("%s is larger\n", file1);
             ^
test.c:32:13: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘struct FILE *’ [-Wformat=]
             printf("%s is larger\n", file2);

错误主要是关于char类型和int类型的类型。 我提到这个页面,只改变了main函数中的一些部分 http://www.c4learn.com/c-programs/c-program-to-compare-two-textdata-files-in-c-programming.html 但是这不适用于从命令行读取文件。

很抱歉打扰了,但这真的令人讨厌这种问题。 请提供必要的帮助。 感谢

0 个答案:

没有答案