SHARE
TWEET

sa1.c

a guest Aug 25th, 2019 37 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <string.h>
  2. #include <unistd.h>
  3. #include <stdlib.h>
  4. #include <stdio.h>
  5. #include <errno.h>
  6.  
  7. #include <sys/types.h>
  8. #include <sys/stat.h>
  9.  
  10. int main(int argc, char *argv[])
  11. {
  12.     int ch;
  13.     char *filename;
  14.     FILE *pf;
  15.  
  16.     if (argc > 1)
  17.     {
  18.         filename = argv[1];
  19.     }
  20.     else
  21.     {
  22.         printf("Usage: %s <file-name-to-read>\n", argv[0]);
  23.         exit(EXIT_SUCCESS);
  24.     }
  25.  
  26.     if (chmod(filename, S_IRUSR | S_IWUSR) < 0)
  27.     {
  28.         perror("chmod()");
  29.         exit(EXIT_FAILURE);
  30.     }
  31.  
  32.     if (access(filename, F_OK) < 0)
  33.     {
  34.         perror("File does not exist");
  35.         exit(EXIT_FAILURE);
  36.     }
  37.  
  38.     if ((pf = fopen(filename, "r")) == NULL)
  39.     {
  40.         perror("fopen()");
  41.         exit(EXIT_FAILURE);
  42.     }
  43.  
  44.     fprintf(stderr, "File %s is opened.\n", filename);
  45.  
  46.     if (chmod(filename, S_IWUSR) < 0)
  47.     {
  48.         perror("chmod()");
  49.         exit(EXIT_FAILURE);
  50.     }
  51.  
  52.     if (access(filename, R_OK) < 0)
  53.     {
  54.         fprintf(stderr, "File can't be read: %s.\n", strerror(errno));
  55.         errno = 0;
  56.     }
  57.     else
  58.     {
  59.         fprintf(stderr, "File is still readable!\n");
  60.         exit(EXIT_FAILURE);
  61.     }
  62.  
  63.     while (! feof(pf))
  64.     {
  65.         if ((ch = fgetc(pf)) >= 0)
  66.         {
  67.             putchar(ch);
  68.         }
  69.     }
  70.  
  71.     fclose(pf);
  72.  
  73.     fprintf(stderr, "File is successfuly readed!\n");
  74.  
  75.     if (chmod(filename, S_IRUSR | S_IWUSR) < 0)
  76.     {
  77.         perror("chmod()");
  78.         exit(EXIT_FAILURE);
  79.     }
  80.  
  81.     return EXIT_SUCCESS;
  82. }
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