【发布时间】:2020-11-24 13:53:28
【问题描述】:
我有一个学校项目,作业是:
创建comp.c 以比较两个文件的内容,仅使用
系统调用:open(),read(),close()(不能使用strcmp(),strncmp(),strlen())
comp.out a.txt b.txt
comp.out 如果两个文件不相同则返回 1,如果它们相同则返回 2
要查看结果,您应该使用命令:echo $?
这是我的代码:
#include<unistd.h>
#include<stdio.h>
#include<stdlib.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(int argc , char * argv[])
{
if(argc != 3)
{
printf("something wrong with variables\n");
exit(-1);
}
char* filename1 = argv[1];
char* filename2 = argv[2];
char* addr1;
char* addr2;
struct stat stat_p1;
struct stat stat_p2;
int fileSize1=0,fileSize2=0;
if( stat (filename1, &stat_p1) == -1)
{
printf("error occurred while attempting to stat %s\n" , filename1);
exit(-2);
}
if( stat (filename2, &stat_p2) == -1)
{
printf("error occurred while attempting to stat %s\n" , filename2);
exit(-2);
}
if((fileSize1=stat_p1.st_size) != (fileSize2=stat_p2.st_size)) //checks if the size is different than its not the same file.
{
return 1;
}
else
{
int fd1,fd2;
if((fd1 = open(filename1 ,O_RDONLY)) < 0)
{
printf("error opening file %s\n",filename1);
exit(-3);
}
if((fd2 = open(filename2 ,O_RDONLY)) < 0)
{
printf("error opening file %s\n",filename2);
exit(-3);
}
addr1 = mmap(NULL, fileSize1+ 1, PROT_READ,MAP_PRIVATE, fd1, 0);
if (addr1 == MAP_FAILED)
{
printf("mmap failed\n");
exit(-4);
}
addr2 = mmap(NULL, fileSize2+ 1, PROT_READ,MAP_PRIVATE, fd2, 0);
if (addr2 == MAP_FAILED)
{
printf("mmap failed\n");
exit(-4);
}
for(int i=0;i<fileSize1+1;i++)
{
if(addr1[i] != addr2[i])
{
return 1;
}
}
close(fd1);
close(fd2);
}
return 2;
}
我使用gcc -o comp.exe comp.c 编译
比我试图在 2 个文本文件之间进行比较
我运行这个命令./comp.exe 1.txt, 2.txt
它失败了:
if( stat (filename1, &stat_p1) == -1)
{
printf("error occurred while attempting to stat %s\n" , filename1);
exit(-2);
}
我已经好几个小时都不知道有什么建议有什么问题 非常感谢
【问题讨论】:
-
我的猜测是您传递的文件的绝对/相对路径无效。也许尝试打印出来并仔细检查它们是否确实正确。
-
如果两个文件不相同则返回 1 ,并且您只检查它们的大小来确定它,
if((fileSize1=stat_p1.st_size) != (fileSize2=stat_p2.st_size)),如果文件大小相同但它们不同怎么办. -
你能用
perror吗? -
int并不总是足够大。正确的类型是off_t。