簡體   English   中英

我不明白我在執行 cp 命令時出了什么問題

[英]I don't understand what's wrong in my implementation of cp command

我正在嘗試使用 C 在 UNIX 上模擬cp 這是我的代碼。

#include <stdio.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>

int main(int argc, char const *argv[])
{
  int src, dest;
  char buff[256];
  int bits_read;

  src = open(argv[1], O_RDONLY);
  dest = open(argv[2], O_WRONLY | O_TRUNC | O_CREAT, 0644);

  if (dest < 0)
    perror("Er");

  while ((bits_read = read(src, buff, sizeof(buff))) > 0)
    if (bits_read != write(dest, buff, sizeof(buff)))
      perror("Er");

  close(src);
  close(dest);

  return 0;
}

我得到以下 output:

Er: Undefined error: 0

我可以看到新文件末尾包含一些重復的行。

最后一行不是 sizeof(buf) 長。
利用

if (bits_read != write(dest, buff, bits_read)) 

有幾個錯誤,有時是邏輯錯誤(例如,寫入需要字節來讀取參數;或者需要以錯誤退出,否則為什么會繼續出現阻塞錯誤),奇怪的命名(例如,大小以字節為單位而不是位),還有樣式代碼之類的錯誤..但這只是一種意見。 無論如何閱讀以下代碼並將其與您的進行比較,我只做了基本的修復,我沒有嘗試過,但我認為可以編譯和運行而不會出錯。 我再說一遍,我只做了一點評論,否則你可能很難理解你的錯誤:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>

int main(int argc, char const *argv[])
{
    int src, dest;
    char buff[256];
    int bytes_read, bytes_wite;

    src = open(argv[1], O_RDONLY);
    dest = open(argv[2], O_WRONLY | O_TRUNC | O_CREAT, 0644);

    if (dest < 0) {
        perror("Er");
        exit (-2);
    }

    while ((bytes_read = read(src, buff, sizeof(buff))) > 0) {
      if (write(dest, buff, bytes_read) == -1) {
          perror("Er2");
          exit (-1);
      }
    }

    close(src);
    close(dest);

    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM