Take the 2-minute tour ×

Whenever I use open I get the permission denied error. But when I use fopen it opens the file fine. What is wrong with my code?

mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
char *filename = "dataread.txt";

rec = open(filename ,O_WRONLY | O_CREAT | O_TRUNC,mode);
if(rec == -1)
    perror("\nopen error 1:");


open error 1:: Permission denied

With fopen I don't get this error.

share|improve this question
filename should be a const char *, by the way. –  Kerrek SB Sep 29 '11 at 14:15
How are you calling fopen? And I removed the C++ tag as I haven't seen any C++. –  user7116 Sep 29 '11 at 14:15
show your fopen code –  KevinDTimm Sep 29 '11 at 14:15
@Kerrek: Why? Just because open takes a const char * (meaning it won't modify the string you pass) doesn't mean you have to use a const char * variable (or any pointer variable whatsoever) to store the address of the string you want to pass. –  R.. Sep 29 '11 at 16:46
R.: Because a string literal is a pointer to non-mutable data. It's not related to the question, just a general point. –  Kerrek SB Sep 29 '11 at 17:09
add comment

1 Answer

up vote 1 down vote accepted

I added an int rec=0; var declaration and the necessary includes files and then compiled your code. It runs with no errors as a normal user in my Fedora 15 laptop. Check the dir/file permissions you are running this on, the problems does not seem to be in the code.

share|improve this answer
add comment

Your Answer


