Skip to content

open()

Purpose

open() opens a file, device node, FIFO, or special file and returns a file descriptor.

For embedded Linux labs, it is commonly used to open /dev/*, /sys/*, regular files, and device interfaces.

#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

Prototype

int open(const char *pathname, int flags, ... /* mode_t mode */);

Parameters

Parameter Description
pathname Path to the file or device node.
flags Access mode and behavior flags, such as O_RDONLY, O_WRONLY, O_RDWR, O_NONBLOCK, or O_CLOEXEC.
mode File permission bits, required when O_CREAT is used.

Return Value

Returns a non-negative file descriptor on success. Returns -1 on failure and sets errno.

Minimal Example

int fd = open("/dev/mygpio", O_RDWR | O_NONBLOCK);
if (fd < 0) {
    perror("open");
    return -1;
}

Common Pitfalls

  • Forgetting to close the file descriptor.
  • Opening a blocking device when the program expects non-blocking behavior.
  • Missing permission or udev rule for /dev/* nodes.
  • Using O_CREAT without providing the mode argument.