+ 3

Can a file be associated with multiple stream objects?

I read in a book that it is a runtime error to attempt to open a file that is already opened (associating another stream object with the same file). To test this, I made the following code: https://code.sololearn.com/ctyASnbmtR2t/#cpp When I ran the code, no runtime errors occurred, but I couldn't explain the reason for the output. Why is it different in the two cases? Why wasn't even a single "Hello\n" printed when the streams weren't tied? And why wasn't two "World\n"'s printed in the second case? Why does the 3rd way work just as intended? Also, does this now mean that multiple streams can point to the same file? Also, is this a form of undefined behavior? If yes, then is the book taking these operations as errors because they have undefined behavior?

1st Dec 2018, 10:37 AM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
3 Answers
+ 2
I'm linking this thread because it has a few other details but primarily: "if this works, behavior's implementation-defined". https://stackoverflow.com/questions/50114099/does-fopen-return-null-pointer-if-file-is-already-open/50114472#50114472 Note, this may help you see what the file pointers are actually doing: cfout1<<"Hello1a\n"; cfout2<<"World2a\n"; cfout1<<"Hello1b\n"; cfout2<<"World2b\n"; (...the 1a/2b stuff)
1st Dec 2018, 5:07 PM
Kirk Schafer
Kirk Schafer - avatar
+ 4
I'm a little fuzzy on this in the spec, but here''s one that appears to use something called a "lock_guard" (C++11): https://stackoverflow.com/questions/33596910/c-how-to-have-multiple-threads-write-to-a-file I also saw forum threads mentioning the use of memory-mapping similar to here: https://stackoverflow.com/questions/823479/multiple-threads-reading-from-the-same-file And other options accommodating threading include locking (my original thought, even just by zones), critical areas, semaphores and mutexes (the link above and this): https://social.msdn.microsoft.com/Forums/vstudio/en-US/9b0e5a50-224b-4f9f-ab0f-9f86572b2baf/writing-to-a-same-file-from-multiple-threads
1st Dec 2018, 9:04 PM
Kirk Schafer
Kirk Schafer - avatar
+ 2
Kirk Schafer Thank you very much for looking into the issue. If the behaviour is implementation defined, then nothing can be said about it. But can it be that C++ did specify a particular behaviour? Because I think multithreading application dealing with files may require multiple threads working on the same file.
1st Dec 2018, 5:20 PM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar