If I open the same file twice, will it give an error, or will it create two different file descriptors? For example
a = open("teste.txt", O_RDONLY);
b = open("teste.txt", O_RDONLY);
Risk Assessment. Simultaneously opening a file multiple times can result in unexpected errors and nonportable behavior.
The same file can be opened more than once in the same program (or in different programs). Each instance of the open file has its own file pointer that can be manipulated independently.
You can definitely open a file for reading more than once, either in the same program, or in different programs. It should have no effect on the program(s).
The open() function opens a file, and returns it as a file object. Read more about file handling in our chapters about File Handling.
To complement what @Drew McGowen has said,
In fact, in this case, when you call open() twice on the same file, you get two different file descriptors pointing to the same file (same physical file). BUT, the two file descriptors are indepedent in that they point to two different open file descriptions(an open file description is an entry in the system-wide table of open files).
So read operations performed later on the two file descriptors are independent, you call read() to read one byte from the first descriptor, then you call again read()on the second file descriptor, since thier offsets are not shared, both read the same thing.
#include <fcntl.h>
int main()
{
// have kernel open two connection to file alphabet.txt which contains letters from a to z
int fd1 = open("alphabet.txt",O_RDONLY);
int fd2 = open("alphabet.txt",O_RDONLY);
// read a char & write it to stdout alternately from connections fs1 & fd2
while(1)
{
char c;
if (read(fd1,&c,1) != 1) break;
write(1,&c,1);
if (read(fd2,&c,1) != 1) break;
write(1,&c,1);
}
return 0;
}
This will output aabbccddeeffgghhiijjkkllmmnnooppqqrrssttuuvvwwxxyyzz
See here for details, especially the examples programs at the end.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With