baobobs
baobobs

Reputation: 703

C File Descriptor is returning -1 on open

Embarrassingly simple question, but I can't seem to open a new file for writing using a file descriptor. Every variation I've tried returns -1. What am I missing? This is how you initialize a file using file descriptors, correct? I can't find documentation that states otherwise.

#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>

int main()
{
  int fd;
  mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
  fd = open ("/home/CSTCIS/sample.dat", O_WRONLY, mode);
  printf("%d\n", fd);
}

perror() prints open: No such file or directory.

Upvotes: 2

Views: 2491

Answers (3)

shauryachats
shauryachats

Reputation: 10385

Quoting pubs.opengroup.org,

Upon successful completion, the [open] function shall open the file and return a non-negative integer representing the lowest numbered unused file descriptor. Otherwise, -1 shall be returned and errno set to indicate the error. No files shall be created or modified if the function returns -1.

To check what the problem is with the open() statement, just write:

perror("open");

before the printf() statement.

OP has found a solution:

The open() command works if O_CREAT flag is included.

fd = open ("/home/CSTCIS/sample.dat", O_WRONLY | O_CREAT, mode);

Upvotes: 5

Bhuvanesh
Bhuvanesh

Reputation: 1279

When we are using the open() function , we can open the file which is already present in our file structure.

If we want to create a new file, then we can use the O_CREAT flag in open() function or we can use the creat() function like this.

   mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
   fd = open ("/home/CSTCIS/sample.dat", O_WRONLY|O_CREAT, mode);

(or)

  fd=creat("/home/CSTCIS/sample.dat",mode);

When we are using the creat() function, it will open the file in read only mode.

Upvotes: 2

baobobs
baobobs

Reputation: 703

Found the problem - this needed to be included among the flags: O_CREAT

Upvotes: 1

Related Questions