Advertisement
Guest User

Untitled

a guest
Apr 21st, 2018
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.02 KB | None | 0 0
  1. /**
  2.  * Napisati fju:
  3.  * void osCatFileFromPos(const char* srcPath, const char* destPath, const off_t pos);
  4.  * koja od pozicije pos nadovezuje fajl sa putanje srcPath na fajl sa putanjom destPath.
  5.  * Ispis nije potreban.
  6. **/
  7. #include <sys/types.h>
  8. #include <sys/stat.h>
  9. #include <unistd.h>
  10. #include <fcntl.h>
  11. #include <stdio.h>
  12. #include <stdlib.h>
  13. #include <string.h>
  14. #include <limits.h>
  15.  
  16. void osCatFileFromPos(const char* srcPath, const char* destPath, const off_t pos);
  17.  
  18. int main(int argc, char** argv) {
  19.     if (argc != 4) {
  20.         exit(EXIT_FAILURE); // usage incorrect
  21.     }
  22.  
  23.     long pos = strtol(argv[3], 0, 10);
  24.     osCatFileFromPos(argv[1], argv[2], (off_t)pos);
  25.  
  26.     exit(EXIT_SUCCESS);
  27. }
  28.  
  29. void osCatFileFromPos(const char* srcPath, const char* destPath, const off_t pos) {
  30.     char* sPath = realpath(srcPath, NULL);
  31.     char* dPath = realpath(destPath, NULL);
  32.  
  33.     if (sPath == NULL) {
  34.         exit(EXIT_FAILURE); // srcPath is NULL
  35.     }
  36.  
  37.     if (dPath != NULL) {
  38.         if (!strcmp(sPath, dPath)) {
  39.             exit(EXIT_FAILURE); // srcPath and destPath are the same.
  40.         }
  41.     }
  42.  
  43.     free(sPath);
  44.     if (dPath != NULL) {
  45.         free(dPath);
  46.     }
  47.  
  48.     int srcFd, destFd;
  49.     if (srcFd = open(srcPath, O_RDONLY) == -1) {
  50.         exit(EXIT_FAILURE); // open failed.
  51.     }
  52.  
  53.     if (destFd = open(destPath, O_RDWR) == -1) {
  54.         exit(EXIT_FAILURE); // open failed
  55.     }
  56.  
  57.     static int bufSize = 1<<13U;
  58.     char* buffer = malloc(bufSize);
  59.     if (buffer == NULL) {
  60.         exit(EXIT_FAILURE); // malloc failed
  61.     }
  62.  
  63.     if (lseek(destFd, (off_t)pos, SEEK_SET) == -1) {
  64.         exit(EXIT_FAILURE); // lseek failed
  65.     }
  66.  
  67.     int readBytes = 0;
  68.     while ( (readBytes = read(srcFd, buffer, bufSize)) > 0) {
  69.         if (write(destFd, buffer, readBytes) != readBytes) {
  70.             exit(EXIT_FAILURE); // write failed
  71.         }
  72.     }
  73.  
  74.     if (readBytes != 0) {
  75.         exit(EXIT_FAILURE); // read failed.
  76.     }
  77.  
  78.     free(buffer);
  79.  
  80.     close(srcFd);
  81.     close(destFd);
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement