I am looking at I/O operations in C++ and I have a question.
When opening a file like:
#include <fcntl.h>
int main() {
unsigned char buffer[16];
int fd = open (argv[1], O_RDONLY);
read(fd, buffer, sizeof(buffer));
return 0;
}
How can the variable fd represent a file as an integer when passing it to the open method? Is it repesenting a file in current folder? If I print the ´fd´variable, it prints 3. What does that mean?
Ps. I know there are several other ways to handle files, like stdio.h, fstream etc but that is out of the scope of this question. Ds.
It’s a handle that identifies the open file; it’s generally called a file descriptor, hence the name
fd.When you open the file, the operating system creates some resources that are needed to access it. These are stored in some kind of data structure (perhaps a simple array) that uses an integer as a key; the call to
openreturns that integer so that when you pass itread, the operating system can use it to find the resources it needs.It’s representing the file that you opened; its filename was
argv[1], the first of the arguments that was passed to the program when it was launched. If that file doesn’t exist, oropenfailed for some reason, then it has the value -1 and doesn’t represent any file; you really should check for that before you try to do anything with it.It doesn’t have any particular meaning; but it has that value because it was the fourth file (or file-like thing) that was opened, after the input (0), output (1) and error (2) streams that are used by
cin,coutandcerrin C++.