C++ CreateFile cant read file ERROR_ACCESS_DENIED [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I'm trying to read file content, but despite it's able to write to same file. I can't read from it! The program is running as Adminstator.
I have Tried to give " FILE_SHARE_WRITE | FILE_SHARE_READ " rights, but still not work.
DWORD dwBytesWritten = 0;
unsigned long BytesRead = 0;
HANDLE hFile = INVALID_HANDLE_VALUE;
wchar_t text_file[MAX_PATH] = { 0 };
TCHAR *save_text(void) {
OPENFILENAME ofn = { 0 };
TCHAR filename[512] = _T("C://Windows/EXAMPLE.txt");
ofn.lStructSize = sizeof(ofn);
ofn.lpstrFilter = L"Txt files (*.txt)\0*.txt\0All Files\0*.*\0";
ofn.lpstrFile = filename;
ofn.nMaxFile = sizeof(filename);
ofn.Flags = OFN_NONETWORKBUTTON | OFN_OVERWRITEPROMPT | OFN_PATHMUSTEXIST | OFN_LONGNAMES | OFN_EXPLORER | OFN_HIDEREADONLY;
ofn.nFilterIndex = 1;
return(filename);
}
void WriteToFile(TCHAR *wText)
{
wchar_t loginchar[1000];
hFile = CreateFile(text_file, FILE_APPEND_DATA, FILE_SHARE_READ, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_HIDDEN, NULL);
WriteFile(hFile, wText, wcslen(wText) * sizeof(wchar_t), &dwBytesWritten, NULL); // its writing without problem
ReadFile(hFile, loginchar, wcslen(loginchar) * sizeof(wchar_t), &BytesRead, NULL); // accses denied
ResultInFile(GetLastError()); // ResultInFile funcitons writes paramater to the file
//ResultInFile(BytesRead); // to see how many bytes read, but of course doesnt work..
CloseHandle(hFile);
}
// this is the how file created at main function :
hFile = CreateFile(txt_file, FILE_APPEND_DATA, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_HIDDEN, NULL);

try:
hFile = CreateFile(text_file, FILE_APPEND_DATA | FILE_READ_DATA, FILE_SHARE_READ, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_HIDDEN, NULL);
instead of:
hFile = CreateFile(text_file, FILE_APPEND_DATA, FILE_SHARE_READ, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_HIDDEN, NULL);
Note that FILE_SHARE_READ allows other calls of CreateFile ask for read permissions, it does not affect the read permissions of your file handle.

Related

DeviceIoControl fails with error 395 to set a reparse point

Recently I posted this question and now I am trying to set a reparse point after a file modification with WordPad app. Currently I checked that the reparse point is a Microsoft tag and I can save the reparse point data in a REPARSE_DATA_BUFFER pointer before the file lose the reparse point. But when I try to set the reparse point to the file, after a file modification, I always get the 395 error with the GetLastError function after call to DeviceIoControl function using the control code FSCTL_SET_REPARSE_POINT. The error 395 doesn't appear in this System Error Codes although I found this error here that has sense. I also removed the discretionary access control list (DACL) from the file, to grants full access to the file by everyone, before try to set the reparse point but I got the same error. Here I put two fragments of my code to get and set the reparse point. I will appreciate any help.
Code to get the reparse point
HANDLE hDevice = CreateFile(
filePath.c_str(), // File path in the computer
0,
FILE_SHARE_READ,
NULL,
OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT,
NULL);
if (hDevice != INVALID_HANDLE_VALUE)
{
size_t maxReparse = MAXIMUM_REPARSE_DATA_BUFFER_SIZE;
rdb = (REPARSE_DATA_BUFFER*)malloc(maxReparse); // rdb was declared as: REPARSE_DATA_BUFFER* rdb;
DWORD outBufferSize = maxReparse;
DWORD bytesReturned = 0;
if (DeviceIoControl(hDevice, FSCTL_GET_REPARSE_POINT, NULL, 0, rdb, outBufferSize, &bytesReturned, NULL))
{
if (rdb != NULL)
{
if (IsReparseTagMicrosoft(rdb->ReparseTag))
{
wprintf(L"Is a Microsoft tag.\n");
}
Code to set the reparse point
LPTSTR pszObjName = const_cast<wchar_t*>(filePath.c_str()); // File path in the computer
PACL newDACL = NULL; // NULL discretionary access control list to grant full access to everyone
DWORD secInfo = SetNamedSecurityInfo(pszObjName, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, NULL, NULL, newDACL, NULL);
if (secInfo == ERROR_SUCCESS)
{
HANDLE hDevice = CreateFile(filePath.c_str(),
GENERIC_ALL, //GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT, NULL);
if (hDevice != INVALID_HANDLE_VALUE)
{
size_t maxReparse = MAXIMUM_REPARSE_DATA_BUFFER_SIZE;
DWORD inBufferSize = maxReparse;
if (rdb != NULL)
{
DWORD bytesReturned = 0;
if (!DeviceIoControl(hDevice, FSCTL_SET_REPARSE_POINT, rdb, inBufferSize, NULL, 0, &bytesReturned, NULL))
{
DWORD error = GetLastError(); // Error 395
unsigned long errorUL = error;
wprintf(L"Error %lu in DeviceIoControl method.\n", errorUL);
}

Reading large mapped text file in C++

I am attempting to display a large amount of text(barely less than 1GB).
My code:
HANDLE hFile;
DWORD dwBytesRead = 0;
OVERLAPPED ol = {0};
HANDLE m_hMapFile;
hFile = CreateFile(_T("test.txt"),
GENERIC_WRITE | GENERIC_READ,
0,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED,
NULL);
m_hMapFile = CreateFileMapping(hFile, NULL, PAGE_READWRITE, 0, 0, NULL);
LPVOID m_lpMapAddress = MapViewOfFile(m_hMapFile, FILE_MAP_ALL_ACCESS, 0,
0, 0);
}
Now that the text file is mapped, how do I display its contents? I have attempted the following (poor) implementation:
char *mappedData = (char*)m_lpMapAddress;
for(int k = 0; k < strlen(mappedData); k++){
cout<<mappedData [k];
}
This is obviously not the right way to display the text contents. Is there a more efficient method?
You may try doing all your output at once:
cout.write(mappedData, mappedSize);
But note that printing a gigabyte of data to console is not likely to be efficient anyhow.
Console output has purpose of being read by user (programmatic parsing is secondary thing). Do you expect user to read 1 GB of data?

How to read something to the RAW disk and then write it some further in C++?

I'd like to first write something to a disk device, then read the same data and write it some further. My code looks like this:
std::string devicePath = "\\\\.\\PhysicalDrive0"; //'0' is only example here
HANDLE source = CreateFile(disk.c_str(), GENERIC_WRITE | GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, NULL, NULL);
BOOST_TEST_REQUIRE(source, "Failed to create file handle.");
std::unique_ptr<CHAR[]> primaryBuffer(new CHAR[DEFAULT_FILESIZE]);
std::unique_ptr<CHAR[]> checkBuffer(new CHAR[DEFAULT_FILESIZE]);
for (auto i = 0; i < DEFAULT_FILESIZE; ++i) {
primaryBuffer[i] = 'x';
checkBuffer[i] = ' ';
}
WriteFile(source, primaryBuffer.get(), DEFAULT_FILESIZE, NULL, NULL);
//Here I move the pointer to write data in new place.
DWORD destination = SetFilePointer(source, DEFAULT_FILESIZE, NULL, FILE_BEGIN);
WriteFile(&destination, source, DEFAULT_FILESIZE, NULL, NULL);
ReadFile(source, primaryBuffer.get(), DEFAULT_FILESIZE, NULL, NULL);
ReadFile(&destination, checkBuffer.get(), DEFAULT_FILESIZE, NULL, NULL);
BOOST_TEST_MESSAGE(checkBuffer.get());
BOOST_TEST_MESSAGE(primaryBuffer.get());
Unfortunately, both buffers are different and I've tried almost everything to check what's wrong. Maybe somebody has any idea what I'm doing wrong?

Using File Mapping to read data from file

I want to read data from a file (.txt) and push into Edit box.
I'm writing C++ with pure API.
HANDLE hFile;
HANDLE hMapFile;
LPVOID pMemory;
and
case IDM_OPEN:
hFile = CreateFile((LPCWSTR)szFileName, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, FILE_ATTRIBUTE_ARCHIVE, NULL);
hMapFile = CreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
pMemory = MapViewOfFile(hMapFile, FILE_MAP_READ | FILE_MAP_WRITE, 0,0,0);
FileSize = GetFileSize(hFile, NULL);
SendMessage(hWndEdit, WM_SETTEXT, 0, (LPARAM)(LPCWSTR)pMemory);
MessageBox(hWnd, (LPCWSTR)pMemory, L"Caption", MB_OK);
UnmapViewOfFile(pMemory);
CloseHandle(hMapFile);
CloseHandle(hFile);
break;
Result: Blank, nothing in Edit box
I search some page but not solved.
When I try debug by set breakpoint like this image:
http://i8.upanh.com/2013/1103/02//57993893.untitled.png
(Sorry I can't post image)
hFile is 0xffffffff, so I think error is CreateFile, but I don't understand !!
Please help me solve this. Thanks !!!
hFile = CreateFile((LPCWSTR)szFileName,....
Why the cast to LPCWSTR? If you need that cast you are doing something wrong. Investigate each step with a debugger to learn more about what is wrong.

OPENFILENAME open dialog

i want to get a full file path by open file dialog in win32.
i do it by this function:
string openfilename(char *filter = "Mission Files (*.mmf)\0*.mmf", HWND owner = NULL) {
OPENFILENAME ofn ;
char fileName[MAX_PATH] = "";
ZeroMemory(&ofn, sizeof(ofn));
ofn.lStructSize = sizeof(OPENFILENAME);
ofn.hwndOwner = owner;
ofn.lpstrFilter = filter;
ofn.lpstrFile = fileName;
ofn.nMaxFile = MAX_PATH;
ofn.Flags = OFN_EXPLORER | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY;
ofn.lpstrDefExt = "";
ofn.lpstrInitialDir ="Missions\\";
string fileNameStr;
if ( GetOpenFileName(&ofn) )
fileNameStr = fileName;
return fileNameStr;
}
it's work fine and return path . but i can't write into the that file i get path of it with openfilename.
note :
i call this code to write to the file (serialization):
string Mission_Name =openfilename();
ofstream ofs ;
ofs = ofstream ((char*)Mission_Name.c_str(), ios::binary );
ofs.write((char *)&Current_Doc, sizeof(Current_Doc));
ofs.close();
Try this for write:
string s = openfilename();
HANDLE hFile = CreateFile(s.c_str(), // name of the write
GENERIC_WRITE, // open for writing
0, // do not share
NULL, // default security
CREATE_ALWAYS, // Creates a new file, always
FILE_ATTRIBUTE_NORMAL, // normal file
NULL); // no attr. template
DWORD writes;
bool writeok = WriteFile(hFile, &Current_Doc, sizeof(Current_Doc), &writes, NULL);
CloseHandle(hFile);
... and read:
HANDLE hFile = CreateFile(s.c_str(), // name of the write
GENERIC_READ, // open for reading
0, // do not share
NULL, // default security
OPEN_EXISTING, // Creates a new file, always
FILE_ATTRIBUTE_NORMAL, // normal file
NULL); // no attr. template
DWORD readed;
bool readok = ReadFile(hFile, &Current_Doc, sizeof(Current_Doc), &readed, NULL);
CloseHandle(hFile);
Help links:
http://msdn.microsoft.com/en-us/library/windows/desktop/bb540534%28v=vs.85%29.aspx
http://msdn.microsoft.com/en-us/library/windows/desktop/aa363858%28v=vs.85%29.aspx
Try closing it and reopen then for writing.