SHARE
TWEET

Untitled

Lexolordan Dec 9th, 2018 67 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <sys/stat.h>
  2. #include <fcntl.h>
  3.  
  4. #include <unistd.h>
  5.  
  6. ssize_t c_write(int fd, const void *buff, int bytesToWrite) {
  7.     size_t bytesWritten;
  8.     for (bytesWritten = 0; bytesWritten < bytesToWrite; ) {
  9.         ssize_t currentlyWritten = write(fd, buff + bytesWritten, bytesToWrite - bytesWritten);
  10.         if (currentlyWritten == 0) {
  11.             return bytesWritten;
  12.         }
  13.  
  14.         if (currentlyWritten == -1) {
  15.             return -1;
  16.         }
  17.  
  18.         bytesWritten += currentlyWritten;
  19.     }
  20.     return bytesWritten;
  21. }
  22.  
  23. ssize_t c_read(int fd, void *buff, int bytesToRead) {
  24.     size_t bytesRead;
  25.     for (bytesRead = 0; bytesRead < bytesToRead; ) {
  26.         ssize_t currentlyRead = read(fd, buff + bytesRead, bytesToRead - bytesRead);
  27.         if (currentlyRead == 0) {
  28.             return bytesRead;
  29.         }
  30.  
  31.         if (currentlyRead == -1) {
  32.             return -1;
  33.         }
  34.  
  35.         bytesRead += currentlyRead;
  36.     }
  37.     return bytesRead;
  38. }
  39.  
  40. int main(int argc, char **argv) {
  41.     int exit_code = 0;
  42.  
  43.     int in = open(argv[1], O_RDONLY);
  44.     if (in == -1) {
  45.         exit_code = 1;
  46.         goto finally;
  47.     }
  48.  
  49.     int out_digits = open(argv[2], O_WRONLY | O_CREAT, 0640);
  50.     int out_other = open(argv[3], O_WRONLY | O_CREAT, 0640);
  51.     if (out_digits == -1 || out_other == -1) {
  52.         exit_code = 2;
  53.         goto finally;
  54.     }
  55.  
  56.     ssize_t in_read, out_d_read, out_o_read;
  57.     char buffer[1024], in_byte;
  58.     int out;
  59.  
  60.     while ((in_read = c_read(in, &buffer, sizeof(buffer))) > 0) {
  61.         for (int i = 0; i < in_read; ++i) {
  62.             in_byte = buffer[i];
  63.             out = '0' <= in_byte && in_byte <= '9'
  64.                 ? out_digits
  65.                 : out_other;
  66.             if (write(out, &in_byte, sizeof(in_byte)) == -1) {
  67.                 exit_code = 3;
  68.                 goto finally;
  69.             }
  70.         }
  71.     }
  72. finally:
  73.     close(in);
  74.     close(out_digits);
  75.     close(out_other);
  76.  
  77.     return exit_code;
  78. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top