C语言 使用POSIX系统调用比较两个文件



这里是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("%sn",buf1);  //works fine till it gets here...
int samefile = strcmp(buf1,buf2);  //Crashes somewhere around here..
if (samefile != 0)
{
    printf("not equlen");
    return(1);
}
else 
{
    printf("equlen");      
    return(2);
}

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

我发现了一些我认为应该给我一些想法,但我不能理解它(链接中的最后一个答案…)。

返回值不相关。

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

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

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

:

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

注意,在调用memcmp之前,您还应该检查src1_size == src2_size

这会导致崩溃,因为缓冲区可能没有null终止。你试图在printf中将它们打印为字符串"%s",并且也执行了一个字符串。

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

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

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

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;
    }

相关内容

  • 没有找到相关文章

最新更新