Advertisement
Guest User

Untitled

a guest
Mar 31st, 2020
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.83 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <fcntl.h>
  5. void copy_file(const char*, const char*);
  6. void cerrar(int fileto, int filefrom, const char *file, const char *file2);
  7. /**
  8.  * main - copy a file.
  9.  * @ac: argc.
  10.  * @av: argv.
  11.  * Return: Always 0.
  12.  */
  13. int main(int ac, char **av)
  14. {
  15.     if (ac != 3)
  16.     {
  17.         dprintf(2, "Usage: cp file_from file_to\n");
  18.         exit(97);
  19.     }
  20.     if (!av[1])
  21.     {
  22.         dprintf(2, "Error: Can't read from file %s\n", av[1]);
  23.         exit(98);
  24.     }
  25.     if (!av[2])
  26.     {
  27.         dprintf(2, "Error: Can't write to %s\n", av[2]);
  28.         exit(99);
  29.     }
  30.     copy_file(av[1], av[2]);
  31.     return (0);
  32. }
  33.  
  34. /**
  35.  * copy_file - copy a file.
  36.  * @file_from: file from.
  37.  * @file_to: file to.
  38.  */
  39. void copy_file(const char *file_from, const char *file_to)
  40. {
  41.     int fileto, filefrom, a;
  42.     char *bf[1024];
  43.  
  44.     filefrom = open(file_from, O_RDONLY);
  45.     if (filefrom < 0)
  46.     {
  47.         dprintf(2, "Error: Can't read from file %s\n", file_from);
  48.         exit(98);
  49.     }
  50.     fileto = open(file_to, O_RDWR | O_CREAT | O_TRUNC, 0664);
  51.     if (fileto < 0)
  52.     {
  53.         dprintf(2, "Error: Can't write to %s\n", file_to);
  54.         exit(99);
  55.     }
  56.     a = read(filefrom, bf, 1024);
  57.     if (a < 0)
  58.     {
  59.         dprintf(2, "Error: Can't read from file %s\n", file_from);
  60.         exit(98);
  61.     }
  62.     if (write(fileto, bf, a) < 0)
  63.     {
  64.         dprintf(2, "Error: Can't write to %s\n", file_to);
  65.         exit(99);
  66.     }
  67.     cerrar(fileto, filefrom, file_from, file_from);
  68. }
  69.  
  70. /**
  71.  * cerrar - close all open files.
  72.  * @filefrom: file from.
  73.  * @fileto: file to.
  74.  * @file: file to.
  75.  * @file2: file from.
  76.  */
  77. void cerrar(int fileto, int filefrom, const char *file, const char *file2)
  78. {
  79.     if (close(fileto) == -1)
  80.     {
  81.         dprintf(2, "Error: Can't close fd %s\n", file);
  82.         exit(100);
  83.     }
  84.     if (close(filefrom) == -1)
  85.     {
  86.         dprintf(2, "Error: Can't close fd %s\n", file2);
  87.         exit(100);
  88.     }
  89.     close(fileto);
  90.     close(filefrom);
  91. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement