Tobiahao

S01_PLIKI_06

Jan 20th, 2018
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.17 KB | None | 0 0
  1. /*
  2. Napisz program, który przeczyta i wypisze na ekran plik tekstowy o dowolnej wielkości. Nazwę pliku należy przekazywać jako argument wywołania programu. W programie nie wolno korzystać z funkcji printf() ani pokrewnych.
  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 BUFFER_SIZE 128
  14.  
  15. const char *argument_number_error = "Niepoprawna liczba argumentow!\n";
  16.  
  17. int main(int argc, char *argv[])
  18. {
  19.     if(argc != 2) {
  20.         write(STDIN_FILENO, argument_number_error, strlen(argument_number_error));
  21.         return EXIT_FAILURE;
  22.     }
  23.  
  24.     int fd;
  25.     char buffer[BUFFER_SIZE];
  26.     int result;
  27.  
  28.     if((fd = open(argv[1], O_RDONLY | 0600)) == -1) {
  29.         perror("open");
  30.         return EXIT_FAILURE;
  31.     }
  32.  
  33.     for(;;) {
  34.         memset(buffer, '\0', BUFFER_SIZE);
  35.         result = read(fd, buffer, BUFFER_SIZE-1);
  36.         if(result == -1) {
  37.             perror("read");
  38.             return EXIT_FAILURE;
  39.         }
  40.         else if(result == 0)
  41.             break;
  42.         else
  43.             write(STDIN_FILENO, buffer, strlen(buffer));
  44.     }
  45.  
  46.     write(STDIN_FILENO, "\n", 1);
  47.  
  48.     if(close(fd)) {
  49.         perror("close");
  50.         return EXIT_FAILURE;
  51.     }
  52.  
  53.     return EXIT_SUCCESS;
  54. }
Add Comment
Please, Sign In to add comment