1

I have made a c code intended to create a file at root directory.

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

const char *path="/";
int main(){
    FILE *fp;
    umask(0);
    chdir(path);

    fp=fopen("test.txt","w+");
    fclose(fp);

    return 0;
}

the compilation gives no errors but when I execute the file, the following error appears:

kwagjj@kwagjj-Inspiron-3420:~$ gcc -Wall a2.c -o a2
kwagjj@kwagjj-Inspiron-3420:~$ ./a2
Segmentation fault (core dumped)

how am I using the umask function wrong?

kwagjj
  • 807
  • 1
  • 13
  • 23
  • How do you know the segmentation fault is caused by `umask`? – Yu Hao Sep 06 '14 at 13:01
  • Use gdb to get the backtrace and add it to your question – mpromonet Sep 06 '14 at 13:05
  • @YuHao uh, your right... I guess the error is basically not because of `umask` but I was assuming that the problem is eventually related to `umask` because I intended `umask` to give the proper permission to fopen and fclose – kwagjj Sep 06 '14 at 13:08
  • 1
    You should check if `fopen` returns `NULL` or not. – pzaenger Sep 06 '14 at 13:09
  • You/your program (probably) does not have permission to create files in the "/" (root) directory. So, what are the permission for "/" and is your program being executed via 'sudo'? – user3629249 Sep 07 '14 at 18:48

1 Answers1

2

My money is on fopen() failing (probably due to insufficient permissions) and returning NULL, and fclose(NULL) causing the segfault.

Community
  • 1
  • 1
NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • then how can I get the proper permission? I used the `umask` to get the permission but it doesn't seem to work – kwagjj Sep 06 '14 at 13:06
  • 1
    @kwagjj `umask` doesn't affect whether your program has the permission to do something. It affects the default permission bits when your program creates files. – Gilles 'SO- stop being evil' Sep 06 '14 at 13:19
  • @NPE thanks I understand what you are trying to say... I've moved on and am trying another way to get the job done – kwagjj Sep 06 '14 at 13:57