Tobiahao

S01_PLIKI_01

Jan 20th, 2018
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.39 KB | None | 0 0
  1. /*
  2. Napisz program, który przepisze z istniejącego pliku tekstowego czterdzieści znaków z początku i czterdzieści znaków z końca do nowego pliku.
  3. */
  4.  
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include <sys/types.h>
  8. #include <sys/stat.h>
  9. #include <fcntl.h>
  10. #include <unistd.h>
  11. #include <string.h>
  12.  
  13. #define READ_FILE_PATHNAME "01.c"
  14. #define NEW_FILE_PATHNAME "01_file"
  15. #define BUFFER_SIZE 40
  16.  
  17. void rewrite_file(int read_fd, int write_fd)
  18. {
  19.     char buffer[BUFFER_SIZE];
  20.     memset(buffer, '\0', BUFFER_SIZE);
  21.  
  22.     if(read(read_fd, buffer, BUFFER_SIZE-1) == -1) {
  23.         perror("read");
  24.         exit(EXIT_FAILURE);
  25.     }
  26.    
  27.     if(write(write_fd, buffer, BUFFER_SIZE-1) == -1) {
  28.         perror("write");
  29.         exit(EXIT_FAILURE);
  30.     }
  31.  
  32.     if(write(write_fd, "\n\n", 2) == -1) {
  33.         perror("write");
  34.         exit(EXIT_FAILURE);
  35.     }
  36. }
  37.  
  38. int main(void)
  39. {
  40.     int read_fd, write_fd;
  41.  
  42.     if((write_fd = open(NEW_FILE_PATHNAME, O_CREAT | O_TRUNC | O_WRONLY, 0600)) == -1) {
  43.         perror("open write");
  44.         return EXIT_FAILURE;
  45.     }
  46.  
  47.     if((read_fd = open(READ_FILE_PATHNAME, O_RDONLY)) == -1) {
  48.         perror("open read");
  49.         return EXIT_FAILURE;
  50.     }
  51.  
  52.     rewrite_file(read_fd, write_fd);
  53.     lseek(read_fd, -40, SEEK_END);
  54.     rewrite_file(read_fd, write_fd);
  55.  
  56.     if(close(read_fd) == -1) {
  57.         perror("close read");
  58.         return EXIT_FAILURE;
  59.     }
  60.  
  61.     if(close(write_fd) == -1) {
  62.         perror("close write");
  63.         return EXIT_FAILURE;
  64.     }
  65.  
  66.     return EXIT_SUCCESS;
  67. }
Advertisement
Add Comment
Please, Sign In to add comment