CodeBlanks Logo Icon CodeBlanks

open and close

Learn file management with open and close.

The open function

open opens a file and returns a file descriptor. It has two forms: open(path, flags) and open(path, flags, mode). The second form is used with O_CREAT when creating a new file.

Flags specify how the file is opened: O_RDONLY read only, O_WRONLY write only, O_RDWR read and write. O_CREAT creates the file if it does not exist, O_TRUNC truncates it if it does. Multiple flags are combined with |.

close and error checking

close(fd) releases an open file descriptor. Always close when done; otherwise you leak descriptors and may hit the process limit.

open returns -1 on error and sets errno. On success it gives a non-negative descriptor. Always check the return value: catch errors with if (fd < 0). close can also fail; checking it is a good habit.

Practice Apply open and close

Get a descriptor with open("/dev/null", O_WRONLY). Check for errors with if (fd < 0); on error print printf("hata\n") and return 1. On success close(fd) and print printf("tamam\n").

Starter code

main.c
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>

// Open /dev/null
// Check for errors
// Close and print tamam

int main(void) {
    return 0;
}

Sample solution

main.c
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>

int main(void) {
    int fd = open("/dev/null", O_WRONLY);
    if (fd < 0) {
        printf("hata\n");
        return 1;
    }
    close(fd);
    printf("tamam\n");
    return 0;
}

Expected output

tamam

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match open flags

Term Meaning
O_RDONLY Read only
O_WRONLY Write only
O_RDWR Read and write
O_CREAT Create file

2 What does open return on failure?

  • 0
  • 1
  • A file descriptor
  • -1 Correct answer

Explanation: open returns -1 on error and sets errno.

3 File permission

Question
int fd = open("/dev/null", O_WRONLY | O_CREAT, ____);
Answer
int fd = open("/dev/null", O_WRONLY | O_CREAT, 0644);

Explanation: 0644 gives the owner read-write and others read.

All lessons in Advanced