使用POSIX系统调用比较2个文件

时间:2014-03-25 17:17:20

标签: c compare system-calls file-descriptor

C新手在这里。

用这个把我的头靠在墙上......:/ 我试图比较未被任何其他进程使用的文件,这意味着它们是静态的,仅使用系统调用。使用fopen()时我没有遇到任何问题但是当使用open(),read()和write()时感觉要复杂得多......

这是我到目前为止所得到的:

...//Some code here to get file descriptors and other file manipulation checks
int one = read(srcfd1,buf1,src1_size); 
int two = read(srcfd2,buf2,src2_size);
printf("%s\n",buf1);  //works fine till it gets here...
int samefile = strcmp(buf1,buf2);  //Crashes somewhere around here..
if (samefile != 0)
{
    printf("not equle\n");
    return(1);
}
else 
{
    printf("equle\n");      
    return(2);
}

所以基本上,我认为我需要做的是比较2个缓冲区,但这似乎不起作用......

我找到了一些我认为应该给我一些想法的东西here,但我无法理解它(链接中的最后一个答案......)。

返回值无关紧要。

感谢我能得到的任何帮助......:/

2 个答案:

答案 0 :(得分:0)

你的缓冲区不是NUL终止的,所以使用strcmp是没有意义的 - 除非你的缓冲区碰巧在某个地方包含0,否则这几乎肯定会失败。此外,您不会说这些文件是文本文件还是二进制文件,但要使其工作(对于文本或二进制文件),您应该更改:

int samefile = strcmp(buf1,buf2);  //Crashes somewhere around here..

为:

int samefile = memcmp(buf1,buf2,src1_size); // use memcmp to compare buffers

请注意,您还应在致电src1_size == src2_size之前检查memcmp

答案 1 :(得分:0)

由于缓冲区可能未终止,因此崩溃。您正在尝试将它们打印为字符串"%s"在printf中也做了strcmp。

您可以在读取调用后尝试null终止缓冲区,然后将它们打印为字符串。

buf1[one] = '\0';
buf2[two] ='\0';

这很可能会修复您的代码。但还有其他几点,

1) Are your buffers sufficiently large as the file?
2) Better to partially read data, than to try to grab everything in one go.
(means use a loop to read data, till it returns a 0) 
like, 
    Assuming the array "buf" is sufficiently large to hold all the file's data.
    The number "512" means,  read will at most try to read 512 bytes and the
    iteration will continue, till read returns 0 (when there is no more data) or 
    may be a negative number, in case of any error. The array's index is getting 
    incremented, by the number of bytes read till now, so that the data does not 
    get overwritten.
    An example - If a file is having say 515 bytes, read will be called thrice. 
    During  the first call it will return 512, for the 2nd call it will return 3
    and the third call will return 0. (read call returns the number of bytes,
    actually  read)   

    index = 0;
    while(  (no_of_bytes_read = read(fd, buf + index, 512)) > 0)
    {
         index = index  +  no_of_bytes_read;

    }