Nikhil CSB
Nikhil CSB

Reputation: 175

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.

Upvotes: 0

Views: 65

Answers (1)

Walter A
Walter A

Reputation: 20002

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

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

Upvotes: 2

Related Questions