f



open file in c / create if file doesn't exist

Hi everyone!

I have a problem with trying to open a file in C.

The following line in my code is suppoed to open a specified file if it
exists and create a new one with this name if one doesn't exist:

if ((shfd = open(argv[2], O_CREAT | O_RDWR, 0644))  < 0)
			my_error("open failed");

If I try to open a file that doesn't exist I get an error:
Bus error

And when it creates a file it sets permissions to -rw------ instead of
-rw-r--r-- as I would hope... Is there something I'm not getting about
how O_CREATE works?...

However, if I try to open existing file that is not empty, it works
fine...

Course anyone please help me?

thank you

0
norm4h8 (3)
4/6/2006 4:36:49 PM
comp.lang.c 30657 articles. 5 followers. spinoza1111 (3246) is leader. Post Follow

4 Replies
695 Views

Similar Articles

[PageSpeed] 48

another important thing - it given an error because I map a portion of
the file in memory, as in

if ((mem = mmap(0,
                   SIZE,
                   PROT_READ | PROT_WRITE,
                   MAP_SHARED,
                   shfd,
				   0)) == (void *)-1)
			my_error("mmap failed");


and then I try to write something into it:

sprintf(mem, "%d", getpid());

The file remains empty and I get the "bus error" message.
any help would be greatly appreciated...

Thanks for your time

0
norm4h8 (3)
4/6/2006 4:41:43 PM
norm4h8@yahoo.com wrote:
> I have a problem with trying to open a file in C.
>
> The following line in my code is suppoed to open a specified file if it
> exists and create a new one with this name if one doesn't exist:
>
> if ((shfd = open(argv[2], O_CREAT | O_RDWR, 0644))  < 0)
> 			my_error("open failed");
>
> If I try to open a file that doesn't exist I get an error:
> Bus error
>
> And when it creates a file it sets permissions to -rw------ instead of
> -rw-r--r-- as I would hope... Is there something I'm not getting about
> how O_CREATE works?...

you're going to want to take this up in comp.unix.programmer.  the
answer you're probably going to get will include the words umask and
ftruncate.

0
tu102 (102)
4/6/2006 5:00:42 PM
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>

shfd = open(argv[2],
                  O_RDWR | O_CREAT,
                  S_IRUSR | S_IWUSR | S_IRGRP |  S_IROTH);
if (shfd < 0) {
   perror("open");
   // exit code here
}
// proceed code here

0
4/13/2006 8:42:57 AM
int rv;
// open fd (last post)

rv = lseek(shfd, SIZE+1, SEEK_SET);
if (rv < 0) {
   // handle error
}

rv = write(shfd, "", 1);
if (rv < 0) {
   // handle error
}

rv = lseek(shfd, 0, SEEK_SET);
   // handle error
}

mem = mmap(0, SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, shfd, 0);
if (mem == MAP_FAILED) {
   // handle error
}

0
4/13/2006 8:47:42 AM
Reply: