Search code examples
ccreatefilewritefile

Creating a file and writing something into it does not work how I wanted it


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,


Solution

  • 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