What are file-open and file-close for?

Hi,
I wonder, why before accessing a file we need to have it opened, and after finishing with it, we need to close it?

If FileA is already open by PtrA, PtrB won't be able to open it as well until FileA is closed by PtrA?

When PtrA opens a file, are any extra resources allocated by that action?

Thank you.
I wonder, why before accessing a file we need to have it opened, and after finishing with it, we need to close it?
Almost all resources have to be aquired, then released.

The filesystem requires you to open a file before you access the content. That's just the way it is.

If FileA is already open by PtrA, PtrB won't be able to open it as well until FileA is closed by PtrA?
No. There is no such restriction on opening files.

When PtrA opens a file, are any extra resources allocated by that action?
Yes, the filesystem has to instantiate a new set of data structures and gives you a handle to them (the file descriptor). It doesn't really matter how many times the file is opened, the process is the same.

Now, using cocurrently opened files is another matter. You have the same concurrency issues as you would with memory or any other shared resource.
Hi kbw,
Thank you very much!

Could you give an example for the new set of data structures which are instantiated and that give the user a handle to them?
Last edited on
There are two levels of data structures involved with opening a file in C++.

1) The data structure maintained by the C++ run time library. This includes the operating system handle for the file, the current input and output position in the file, formatting flags, error flags, open mode, stream buffer, etc. You can get an idea for these elements by looking at the documentation for fstream and iostream and the classes they inherit from.
http://www.cplusplus.com/reference/fstream/fstream/
http://www.cplusplus.com/reference/istream/iostream/

2) The data structure maintained by the operating system. This varies by operating system and is generally not visible to the user.

edit: If you didn't open a file, you would have to specify the path name to the file and keep track of your current position in the file and specify that on every call to read or write. Plus, there would be a lot more overhead. Things like file securtiy is checked once when you open the file. You don't want that being done every time you read or write from the file. Also, when you open a file, the OS has to locate the file in the directory and on the disk. You don't want that being done on every access to the file.

Last edited on
Topic archived. No new replies allowed.