inquisitivemongoose
inquisitivemongoose

Reputation: 386

If the open() system call fails to complete, do we need to call close()?

If open() returns a value of -1 to my program, which indicates a failure, do I still need to close the file? I read that if fopen() fails, then you do not need to call fclose() since you have not opened any files. I was wondering if this was the case for open() as well?

int fd = open(myfile, O_RDONLY);

if (fd == -1) {
  close(fd);
}

Upvotes: 2

Views: 1363

Answers (1)

Joshua
Joshua

Reputation: 43317

No.

-1 isn't a file handle, so there's no need or reason to close it.

You could have answered your own question by checking the return value of close(-1). It returns -1, so that call was in error.

Upvotes: 2

Related Questions