0

I have a question about FILE_ATTRIBUTE_TEMPORARY marked files. First of all, here is what I want to do:

I have a DLL, that takes a Filename, and opens that file internally and reads from it. I do not know how this file is handled inside. The file I want to give to that DLL will be created by my process. It must be a temporary file and its data must be held only in RAM and must not be accessed by other processes. So I use the Win32 function CreateFile() with the FILE_ATTRIBUTE_TEMPORARY and the FILE_FLAG_DELETE_ON_CLOSE. This so far works, fine.

I have a tes code where I test if the file can be accessed a second time, while still opened. Here it is:

HANDLE WINHandle = CreateFile("TempFileWIN.txt", (GENERIC_WRITE | GENERIC_READ) ,(FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE), 0, CREATE_ALWAYS, (FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE), 0);

ifstream ifs("TempFileWIN.txt", (ios::in | ios::trunc));

if(ifs.is_open())
{
    cout << "Success!" << endl;
}
else if(ifs.fail())
{
    cout << "Failed!" << endl;
}

I am using the fstream to test if the file could be opened with a stream. That code up there doesn't work. The output is "Failed!". I know, that the file could be opened with the CreateFile a second time. I checked that out. But want to know if it is possible to open the file by an external DLL that works with (e.g.) a fstream.

I hope you can help me with this matter. Best regards.

Edit: Maybe a better question is how I can lock a file to my process and ensure, that it can never be accessed by an other process (even if my process is killed). The file must be openable with C++ fstream object.

Silvio Mayolo
  • 62,821
  • 6
  • 74
  • 116
schieska
  • 253
  • 1
  • 3
  • 8

1 Answers1

0

If I were you, I would keep the handle of the open file, and pass it to the DLL code, and not use the filename, since you're likely to run into access restrictions at some point if you try to access a temporary, delete-on-close file using 'normal' file access.

It is possible to use a Windows handle in a fstream object as described in this answer: https://stackoverflow.com/a/476014/393701

Community
  • 1
  • 1
SirDarius
  • 41,440
  • 8
  • 86
  • 100