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

N

norm4h8

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
 
N

norm4h8

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
 
T

tedu

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.
 
C

Chandra Kalle

#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
 
C

Chandra Kalle

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
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top