#include <iostream>
#include <unistd.h>
int main() {
int file_desc = open("example.txt", O_RDONLY);
if (file_desc == -1) {
std::cout << "Error opening the file\n";
return 1;
}
// Perform operations using file_desc
close(file_desc);
return 0;
}
#include <iostream>
: Includes the input/output stream library for handling standard input and output.#include <unistd.h>
: Includes the Unix Standard function definitions, including open()
and close()
for file operations.int main()
: Entry point of the program.int file_desc = open("example.txt", O_RDONLY);
: Opens a file named "example.txt" in read-only mode (O_RDONLY
) and stores the file descriptor in the variable file_desc
.if (file_desc == -1)
: Checks if there was an error opening the file. If the open()
function returns -1
, an error occurred.std::cout << "Error opening the file\n";
: Prints an error message to the standard output if there was an issue opening the file.return 1;
: Exits the program with a non-zero status, indicating an error occurred during file opening.- Operations using
file_desc
: Perform read/write operations or other file-related actions using the obtained file descriptor. close(file_desc);
: Closes the file associated with the file descriptor file_desc
.return 0;
: Exits the program with a status of 0, indicating successful execution.