If I do an opendir() under Posix or a FindFirstFile() under Windows. Do these operations get a snaphot of the directory contents ? I.e. a readdir() or FindNextFile() wouldn't get additional files added to the directory after opedir() or FindFirstFile() ?
Does opendir() / FindFirstFile() get a snapshot of a directory?
87 Views Asked by Edison von Myosotis At
2
There are 2 best solutions below
0
On
For my Windows system with WSL2 and my Ubuntu PC readdir does not take a snapshot:
#include <iostream>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <dirent.h>
using namespace std;
int main()
{
constexpr char const *FILENAME = "file.bin";
unlink( FILENAME );
DIR *dir = opendir( "." );
if( !dir )
return EXIT_FAILURE;
if( creat( FILENAME, 0 ) == -1 )
return EXIT_FAILURE;
for( dirent *de; de = readdir( dir ); )
cout << de->d_name << endl;
return !errno ? EXIT_SUCCESS : EXIT_FAILURE;
}
With my Windows 11 PC it's the same:
#include <Windows.h>
#include <iostream>
using namespace std;
int main()
{
constexpr wchar_t const *FILENAME = L"file.bin";
DeleteFileW( FILENAME );
WIN32_FIND_DATAW fdw;
HANDLE hFind = FindFirstFileW( L"*", &fdw );
auto ret = [] { return GetLastError() == ERROR_FILE_NOT_FOUND ? EXIT_SUCCESS : EXIT_FAILURE; };
if( hFind == INVALID_HANDLE_VALUE )
return ret();
HANDLE hFile = CreateFileW( FILENAME, GENERIC_READ | GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
if( hFile == INVALID_HANDLE_VALUE )
return EXIT_FAILURE;
do
wcout << fdw.cFileName << endl;
while( FindNextFileW( hFind, &fdw ) );
return ret();
}
Both programs find file.bin, although this isn't guaranteed.
No. For WIn32, see the question linked in the comment. For
opendir, see the documentation of readdir.(emphasis mine)