简体   繁体   中英

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

I'm trying to simulate cp on UNIX using C. Here's my code.

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

I'm getting the following output:

Er: Undefined error: 0

I can see that the new file contains some repeated lines at the end.

The last line is not sizeof(buf) long.
Use

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

There are several errors, sometime of logic (eg. the write need the bytes to read in parameter; or need to exit with an error otherwise why continue with a blocking error), strange naming (eg. the size is in Bytes not in bit), there are error also like style code.. but is only an opinion. Anyway read the follow code and compare it with the your, I made only the basic Fix, I don't tried it but I think can be compiled and runned without errors. I repeat, I made only a little review in otherway could be hard gor you understand your mistakes:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM