cheader-filesfcntl

programm can not find constant in libary fcntl.h in c


I am learning C and somehow my programm can not find a constant defined in a libary. In my understanding S_IRUSR|S_IWUSR shoud be defined in fcntl.h, but I get while trying to compile this error: ... error: 'S_IRUSR' undeclared (first use in this function) ... error: 'S_IWUSR' undeclared (first use in this function)

My programm looks like this:

#include <stdio.h> 
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>

int main(int argc, char *argv[]){

  int filedeskriptor;
  char SchreibeTxt [100] = "Hallo getMonth", LeseTxt [100];

  filedeskriptor = open("getMonthTxt", O_RDWR|O_CREAT, S_IRUSR|S_IWUSR);
  if (filedeskriptor == -1){
    printf("Fehler beim Öffnen von mydat \n");
    exit (EXIT_FAILURE);
  }
  if (write(filedeskriptor, SchreibeTxt, sizeof(SchreibeTxt)) == -1){
    printf("Fehler beim Schreiben in mydat \n");
    exit (EXIT_FAILURE);
  }
  printf("In getMonthTxt geschrieben: %s \n", SchreibeTxt);
  close(filedeskriptor);

  return EXIT_SUCCESS;
}

Any help?

Thanks


Solution

  • It depends on according to which POSIX-version your compiler and implementation is build up to, because S_IRUSR and S_IWUSR are only provided inside of fcntl.h in POSIX.1-2008 as Ian Abbott said in the comments.

    If your compiler uses a preceding POSIX-version, the macros S_IRUSR and S_IWUSR are not defined in fcntl.h as you can see here. They are then defined in the header sys/stat.h.

    Here is a link to the description about the content of the header sys/stat.h, where you can find those:

    https://pubs.opengroup.org/onlinepubs/007908799/xsh/sysstat.h.html


    So if your compiler uses a version predating POSIX.1-2008, add #include <sys/stat.h> at the top of your code or otherwise if you don´t need anything from fcntl.h replace it with that.