【问题标题】:Compare 2 files using POSIX system calls使用 POSIX 系统调用比较 2 个文件
【发布时间】:2014-03-25 17:17:19
【问题描述】:

这里是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);
}

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

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

返回值无关紧要。

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

【问题讨论】:

    标签: c compare system-calls file-descriptor


    【解决方案1】:

    您的缓冲区不是 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

    【讨论】:

      【解决方案2】:

      这会崩溃,因为缓冲区可能不是以空值终止的。您正尝试在 printf 中将它们打印为字符串 "%s" 并执行 strcmp。

      您可以在 read 调用之后尝试 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;
      
          }
      

      【讨论】:

      • Tanmoy,这很有趣 - 你能否详细说明如何部分读取数据 - 我曾尝试过这一点,但无法使其工作。我想我对 read() 如何“在幕后”工作缺乏一些基本的了解......
      • @user3037474,我在回答中添加了更多解释。希望这会有所帮助。
      猜你喜欢
      • 1970-01-01
      • 2011-02-12
      • 1970-01-01
      • 2021-06-21
      • 2016-09-03
      • 1970-01-01
      • 1970-01-01
      • 2022-12-21
      • 1970-01-01
      相关资源
      最近更新 更多