cgccpermissionsraspberry-pi4raspbian-buster

Setting Permissions to a file in C to Read Only


I'm new to C programming and I'm trying to experiment with setting the permissions of a file to Read Only. I'm sure that I don't have the directives correct and when I try to compile I get the error on the line that #include <io.h> is on "fatal error: io.h no such file or directory". The file 'time.log' is in a directory called 'time_logs' and the program will run from the same directory that the directory 'time_logs' is in.

OS is Rasbian for Raspberry Pi 4 Arm Using GCC

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <io.h>
#include <sys.h>


struct stat st = {0};

int main(void){


      if(_chmod("time_logs/time.log", _S_IREAD) == -1)
         perror("Not found");

        else{
              _chmod("time_logs/time.log", _S_IREAD);

             }
}





Solution

  • It looks like you used a Windows manual trying to code for Linux.

    #include <unistd.h>
    #include <sys/stat.h>
    
          if(chmod("time_logs/time.log", S_IRUSR | S_IRGRP | S_IROTH) == -1)
             perror("time_logs/time.log");
    

    But most people just type the permission bits directly. This would be 0444. Adjust to taste.