-2

This is a piece of my code:

    #include <stdio.h>
    #include <windows.h>
    #include <iostream.h>
    #include <signal.h>
    #include <tchar.h>
    #include <stdarg.h>

    int main(int argc, char * agrv[]) {

        //Convert argument 2 to wide char pointer
        wchar_t w[MAX_PATH];
        size_t size_of_w = sizeof(w);
        mbstowcs_s(&size_of_w, w, argv[1], MAX_PATH);
        LPWSTR pFile = w;

        //Copy original file to temp file
        if (!CopyFile(w, L"temp.out", False))
        {
            printf("Error: could not copy file.");
            printf("CopyFile Errorcode %d\n", GetLastError());
            return 1;
        }
        pFile = L"temp.out";

        HANDLE hFile = CreateFile(pFile, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

        if (hFile == INVALID_HANDLE_VALUE)
        {
            printf("Error: could not create handle to file");
            printf("CreateFile Errorcode %d\n", GetLastError());
            return 1;
        }
        printf("Successfully created Handle");
        return 0;
    }

Im trying to open a handle for the newly copied file "temp.out", but an error is thrown and it doesnt work.

My debug print (printf("CreateFile Errorcode %d\n", GetLastError());) prints "CreateFile Errorcode: 2" (File not found) but it is found, becasue CopyFile works just well.

EDIT: I've used absolute path, now, when Im trying to map the file to the memory using the handle, it throws '6', which means invalid handle:

    HANDLE pMap = CreateFileMapping(hFile, NULL, PAGE_EXECUTE_READWRITE,0 ,0 ,NULL);
        LPVOID lpBase MapViewOfFile(pMap, FILE_MAP_ACCESS| FILE_MAP_EXECUTE, 0, 0, 0);
        printf("CreateFileMapping Errorcode %d\n", GetLastError());
        if (!lpBase)
        {
            printf("Error: could not map file to memory");
            printf("CreateFileMapping Errorcode %d\n", GetLastError());
            return 1;
        }
        printf("Successfully mapped file");

EDIT 2:

Ive added error handling to CopyFile, but it works OK and DOES copy the file. the output is now:

program.exe shit.txt Successfully created Handle Error: could not map file to memory createMapFile errorcode: 6

  • the directory has to exist – paulm Aug 04 '15 at 06:58
  • what do you mean, It does exist... Im running it within a directory that has a file in it and it copies the file and names it temp.out @paulm – johnny bravo Aug 04 '15 at 07:00
  • Try using absolute file paths. – sashoalm Aug 04 '15 at 07:02
  • 1
    You are calling `GetLastError` at the wrong time. The [documentation](https://msdn.microsoft.com/en-us/library/windows/desktop/aa363858.aspx) specifically notes to call `GetLastError`, if the function fails. You are calling it unconditionally. – IInspectable Aug 04 '15 at 07:16
  • 1
    I wonder why seemingly so many people make this basic mistake. – Jonathan Potter Aug 04 '15 at 07:21
  • Yes, the error handling is off. Try to fix that up and edit the question to include code with correct error handling. Do check for errors on all api calls. – David Heffernan Aug 04 '15 at 07:22
  • @Jonathan It is frustrating. Especially when askers often don't seem to care when you point this out. I suspect many of them remove the error checking code after having debugged it, believing that the errors won't happen anymore! – David Heffernan Aug 04 '15 at 07:23
  • I did not understand. how can I handle the error if not like that? where should I use `GetLastError`? – johnny bravo Aug 04 '15 at 07:24
  • 1
    @johnnybravo Unless `CreateFile` returns `INVALID_HANDLE_VALUE` you don't have an error to handle. – Jonathan Potter Aug 04 '15 at 07:25
  • @JonathanPotter Ok, but on the next function (EDIT), the handle turns out invalid.. why is this happening? – johnny bravo Aug 04 '15 at 07:26
  • 1
    On the next function you're doing the same thing (and actually that code won't even compile as shown). *DON'T CALL GETLASTERROR() UNLESS SOMETHING FAILS*. – Jonathan Potter Aug 04 '15 at 07:27
  • I realized my mistake with GetLastError.. Such a dumb one – johnny bravo Aug 04 '15 at 07:29
  • although I did what you said and called GetLastError only after the error occured (inside the if) and its the same error again, (when trying to map the file) 6. – johnny bravo Aug 04 '15 at 07:31
  • Dude... you are calling `GetLastError` before checking for an error condition. Can this really be **this** hard to understand? – IInspectable Aug 04 '15 at 07:37
  • @IInspectable I changed that in my code.. Now I edited that here as well.. – johnny bravo Aug 04 '15 at 07:39
  • You also need to call `GetLastError` immediately, and save away the answer. What if the call to `printf` clears the error? And you don't check `CopyFile` for errors. Please fix your error handling. – David Heffernan Aug 04 '15 at 07:49
  • @DavidHeffernan can printf make an "invalid handle" error?! also, I chaged the code and added edits. – johnny bravo Aug 04 '15 at 08:27
  • This is a classic example of the asker that doesn't want to learn. You have bigger problems than the specifics of this question. You don't understand Win32 error handling and you don't seem to want to learn. Why not? – David Heffernan Aug 04 '15 at 08:35
  • @DavidHeffernan that isnt true.. Do I need to learn win32 error handling? fine. – johnny bravo Aug 04 '15 at 08:38
  • Yes you do need to learn error handling. It's absolutely critical. – David Heffernan Aug 04 '15 at 08:39

1 Answers1

0

There is no <iostream.h>, consider using a new compiler!

You can use wmain to avoid string conversion. Although you don't really need that, and you don't need to create a file. Use INVALID_HANDLE_VALUE instead of hFile

#include <iostream>
#include "windows.h"

int wmain(int argc, wchar_t* argv[])
{
    const int buflen = 1000;
    wchar_t* mapName = L"MyMapName";
    wchar_t* message = L"123\0";

    HANDLE hFileMapping = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, buflen, mapName);
    if (!hFileMapping)
    {
        printf("CreateFileMapping error %d\n", GetLastError());
        return 1;
    }

    LPVOID buf = MapViewOfFile(hFileMapping, FILE_MAP_ALL_ACCESS, 0, 0, buflen);
    if (!buf)
    {
        printf("MapViewOfFile error %d\n", GetLastError());
        CloseHandle(hFileMapping);
        return 1;
    }
    CopyMemory(buf, message, (wcslen(message) * sizeof(wchar_t)));
    system("pause");//wait until another program reads this data
    UnmapViewOfFile(buf);
    CloseHandle(hFileMapping);
    return 0;
}

If you use a real file handle instead of INVALID_HANDLE_VALUE then use this method instead (note, buflen is zero): CreateFileMapping(hFile, NULL, PAGE_READWRITE, 0, 0, mapName);

In another program:

int wmain()
{
    const int buflen = 1000;
    wchar_t* mapName = L"MyMapName";
    HANDLE hMapFile = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, mapName);
    if (!hMapFile)
    {
        DWORD e = GetLastError();
        printf("OpenFileMapping %d\n", e);//EDITED: this line was missing
        return 1;
    }

    wchar_t* buf = (wchar_t*)MapViewOfFile(hMapFile, FILE_MAP_ALL_ACCESS, 0, 0, buflen);
    if (!pBuf)
    {
        DWORD e = GetLastError();    
        printf("MapViewOfFileerror %d\n", e);//EDITED: this line was missing
        CloseHandle(hMapFile);
        return 1;
    }
    wcout << buf << endl;
    UnmapViewOfFile(buf);
    CloseHandle(hMapFile);
    return 0;
}
Barmak Shemirani
  • 30,904
  • 6
  • 40
  • 77