-1

I write the following code:

      #include <windows.h>
      #include "stdbool.h"
      #include <winuser.h>
      #include <WinDef.h>
      #include <Winerror.h>
      #include <stdio.h>
      #include <Strsafe.h>

      #define MAX_SIZE 100


         void DisplayError(LPTSTR lpszFunction) 
         // Routine Description:
        // Retrieve and output the system error message for the   last-error code
        { 
          LPVOID lpMsgBuf;
          LPVOID lpDisplayBuf;
          DWORD dw = GetLastError(); 

         FormatMessage(
                    FORMAT_MESSAGE_ALLOCATE_BUFFER | 
                    FORMAT_MESSAGE_FROM_SYSTEM |
                    FORMAT_MESSAGE_IGNORE_INSERTS,
                    NULL,
                    dw,
                    MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
                    (LPTSTR) &lpMsgBuf,
                     0, 
                     NULL );

            lpDisplayBuf = 
               (LPVOID)LocalAlloc( LMEM_ZEROINIT, 
                        ( lstrlen((LPCTSTR)lpMsgBuf)
                          + lstrlen((LPCTSTR)lpszFunction)
                          + 40) // account for format string
                        * sizeof(TCHAR) );

if (FAILED( StringCchPrintf((LPTSTR)lpDisplayBuf, 
                 LocalSize(lpDisplayBuf) / sizeof(TCHAR),
                 TEXT("%s failed with error code %d as follows:\n%s"), 
                 lpszFunction, 
                 dw, 
                 lpMsgBuf)))
{
    printf("FATAL ERROR: Unable to output error code.\n");
}

printf(TEXT("ERROR: %s\n"), (LPCTSTR)lpDisplayBuf);

LocalFree(lpMsgBuf);
LocalFree(lpDisplayBuf);

   }


   int main(){
    //parameters of CreateFile()
     HANDLE hFile;  
     LPCTSTR lpFileName; 
     DWORD dwDesiredAccess; 
     DWORD dwShareMode;
     LPSECURITY_ATTRIBUTES lpSecurityAttributes;
     DWORD dwCreationDisposition; 
     DWORD dwFlagsAndAttributes; 
     HANDLE hTemplateFile; 

     //parameters of WriteFile()

     DWORD nNumberOfBytesToWrite;
     DWORD numberOfBytesWritten;
     LPOVERLAPPED lpOverlapped;
     char DataBuffer[MAX_SIZE];

     //others
     BOOL bErrorFlag; 

     //initialize args of CreateFile()
     lpFileName = "C:\\file.txt";
     dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
     dwShareMode = 0;
     lpSecurityAttributes = NULL;
     dwCreationDisposition = CREATE_NEW;
     dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL; 
     hTemplateFile = NULL; 

     //initialize args of WriteFile()
     strcpy(DataBuffer, "This is the test file");
     nNumberOfBytesToWrite = (DWORD)strlen(DataBuffer);
     numberOfBytesWritten = 0;
     lpOverlapped = NULL;





   hFile = CreateFile(lpFileName, dwDesiredAccess, dwShareMode,
                    lpSecurityAttributes, dwCreationDisposition, 
                    dwFlagsAndAttributes, hTemplateFile);


if (hFile == INVALID_HANDLE_VALUE) 
{ 
    DisplayError(TEXT("CreateFile"));
    printf(TEXT("Terminal failure: Unable to open file \"%s\" for write.\n"), lpFileName);
    return;
}

printf(TEXT("Writing %d bytes to %s.\n"), nNumberOfBytesToWrite, lpFileName);

bErrorFlag = WriteFile(hFile, DataBuffer, nNumberOfBytesToWrite,
         &numberOfBytesWritten, lpOverlapped);
if (FALSE == bErrorFlag)
{
    DisplayError(TEXT("WriteFile"));
    printf("Terminal failure: Unable to write to file.\n");
}
else
{
    if (numberOfBytesWritten != nNumberOfBytesToWrite)
    {
        // This is an error because a synchronous write that results in
        // success (WriteFile returns TRUE) should write all data as
        // requested. This would not necessarily be the case for
        // asynchronous writes.
        printf("Error: dwBytesWritten != dwBytesToWrite\n");
    }
    else
    {
        printf(TEXT("Wrote %d bytes to %s successfully.\n"), numberOfBytesWritten, lpFileName);
    }
}

CloseHandle(hFile);
}

So, as you can see. A program that should create a file named file.txt to the desktop and write a little text into it. I use Microsoft Visual C++ Express, it compiles without errors..but when i let run it by clicking the green play-button, then I see not such a file created on my desktop.

By searching my possible faults, I have also read on https://msdn.microsoft.com/en-us/library/windows/desktop/bb540534%28v=vs.85%29.aspx that they use nearly the same code. Except that I do not include the displaying error parts.

So, my question: What could be the reason why it does not work? Do I (the program) need some extra permissions to do that? For example, I wrote the same in Ubuntu with open() & write() except that I use "/tmp/file.txt" as destionation directory. And it works without additional permissions.

best regards,

user3097712
  • 1,565
  • 6
  • 27
  • 49
  • Just for fun, *do* include the "displaying error parts". What do they tell you? – Jongware Mar 14 '15 at 15:39
  • so, i added the display error parts from the link. But again, program.exe will be terminated with 0 (0x0). nothing is displayed – user3097712 Mar 14 '15 at 16:13
  • You should compile with all warnings & debug info (e.g. `gcc -Wall -Wextra -g`) then learn how to **use the debugger** (e.g. `gdb`) – Basile Starynkevitch Mar 14 '15 at 16:14
  • i think you misunderstood the question. I dont use linux ubuntu for that. if i would, believe me, i would not ask anything :) i try the same what i do in linux now also in windows...but it does not work....the whole thing sucks in windows – user3097712 Mar 14 '15 at 16:33
  • this function: 'void DisplayError(LPTSTR lpszFunction) ' can be replaced with perror() and/or strerror(), both of which are available in all modern versions of C – user3629249 Mar 14 '15 at 18:49

2 Answers2

1

This is the wrong way to write the filename

"C:\Desktop\file.txt";

you need to escape the '\', the \f is actually a escape sequence

"C:\\Desktop\\file.txt";

and also, the file will not be created on your desktop apparently, try this instead

"C:\\file.txt";

and check your C: drive to see the file.

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
  • thank you, I added it (both of your answers) but in both of the two cases it is still not working. I see not file in C or on my desktop. In the debug window, I get still the message that all dll.´s like ntdll and so on are loaded but in the last line it says, that the code is terminated with 0 (0x0) – user3097712 Mar 14 '15 at 13:12
  • `0 (0x0)` means success there must be something else happening, I see that your code lacks any success check after `CreateFile()` and also if you are learning you should use standard functions like `fopen(filename, "w");` to open a file for writing that will be created if it doesn't exist. – Iharob Al Asimi Mar 14 '15 at 13:15
  • hmmh, so I get a success message from the IDE although it is not created? strange. Yeah, I leave out the checks because I wanted it small as possible, not putting big overhead at my first try with windows – user3097712 Mar 14 '15 at 13:20
  • The IDE doesn't care if it was created or not, it's your program that is reportnig success you must check for errors yourself. – Iharob Al Asimi Mar 14 '15 at 13:23
  • now, I have edited my code a little bit. I put an if-statement as you can see. Now, in the debug window it says that program.exe is terminated with 259 (0x103). – user3097712 Mar 14 '15 at 15:37
1

The code is using the wrong path to your Desktop directory.

For Windows 7 (and most versions of windows) the path would be:

be sure to use two backslashs at each directory level

C:\Users\yourUsername\Desktop

user3629249
  • 16,402
  • 1
  • 16
  • 17
  • holy sh**....yeah, it works !!! Thank you for your helpful comment/answer. Forget about the checks or whatever...what i have learned is: the devil is in the detail . – user3097712 Mar 14 '15 at 20:56
  • If this was the error "behind" the question, you may be interested in finding the desktop programmatically: http://stackoverflow.com/questions/17933917/get-the-users-desktop-folder-using-windows-api – Jongware Mar 14 '15 at 22:19