Question

I am trying to open a text file. if the file does not exists, then it must be first created and opened. I have written the following piece of code for this purpose. The code works fine, it also creates file inside BIN folder but still I cannot see any file get opened when I exexute this code. Please tell what is wrong with my code.

CODE SNIPPET:

#include "stdafx.h"
#include <windows.h>
#include <iostream>
#include <string>
using namespace std;

int WINAPI WinMain( HINSTANCE hInst, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd )
{
  HANDLE  hFile;
  DWORD dwBytesRead, dwBytesWritten, dwPos;
  TCHAR szMsg[1000];

    hFile = CreateFile (("File.txt"),      // Open File.txt.
                        GENERIC_WRITE,          // Open for writing
                        0,                      // Do not share
                        NULL,                   // No security
                        OPEN_ALWAYS,            // Open or create
                        FILE_ATTRIBUTE_NORMAL,  // Normal file
                        NULL);                  // No template file

  if (hFile == INVALID_HANDLE_VALUE)
  {
    wsprintf (szMsg, TEXT("Could not open File.txt"));
    CloseHandle (hFile);            // Close the file.
    return 0;
  }

return 0;
}
Was it helpful?

Solution

I thought the parameter "OPEN_ALWAYS" of CREATE_FILE() will open the text file in front of me

No, it won't actually open the file in front of you as if you had double-clicked on it in Explorer.

Instead, what the OPEN_ALWAYS parameter means is to open a handle to the file so that, for example, you can read from or write to it programmatically. If you specify OPEN_ALWAYS, the CreateFile function will succeed in creating the file and opening a handle to it, even if the file already exists.

If you don't want that behavior, you can specify OPEN_EXISTING, which opens a handle to a file (or device) only if it already exists. If it does not exists, the CreateFile function will return an error.

Remember, as others have pointed out, that you need to follow each successful call to CreateFile with a call to CloseHandle. This ensures that the handle you've opened to the file (or device) is properly freed and prevents your application from leaking resources. But you only need to do this if the call to CreateFile succeeded. If it failed, returning INVALID_HANDLE_VALUE, you should not call CloseHandle for that handle.

int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
{
    HANDLE hFile;
    DWORD  dwBytesRead, dwBytesWritten, dwPos;
    TCHAR  szMsg[1000];

    // If the file already exists, open a handle to it for writing.
    // If the file does not exist, create it and then open a handle to it.
    hFile = CreateFile(TEXT("File.txt"),       // Open File.txt.
                       GENERIC_WRITE,          // Open for writing
                       0,                      // Do not share
                       NULL,                   // No security
                       OPEN_ALWAYS,            // Open or create
                       FILE_ATTRIBUTE_NORMAL,  // Normal file
                       NULL);                  // No template file

    // Test for and handle failure...
    if (hFile == INVALID_HANDLE_VALUE)
    {
        wsprintf(szMsg, TEXT("Could not open File.txt"));
        MessageBox(NULL, szMsg, NULL, MB_OK | MB_ICONERROR);
        // don't close the file here because it wasn't opened!
        return 0;
    }

    // Read from, write to, or otherwise modify the file here,
    // using the hFile handle.
    // 
    // For example, you might call the WriteFile function.
    // ...

    // Once we're finished, close the handle to the file and exit.
    CloseHandle (hFile);            // Close the file.
    return 0;
}

There is a complete sample available on MSDN: Opening a File for Reading or Writing

If you want to open the text file as if you'd double-clicked it in Explorer, you need to use the ShellExecute function. It does not require a handle to the file, just the path. Naturally, the open verb is the one you want to specify. Note that you should not have an open handle to the file when you try to open it with ShellExecute. If you've opened/created the file using CreateFile, make sure to call CloseHandle before calling ShellExecute.

OTHER TIPS

First of all, if hFile is an INVALID_HANDLE_VALUE there is no need to call CloseHandle. Remove that statement. Also, it is better if you CloseHandle before returning because it's always nice to free any resources you use. If you copied this code to a function and some huge application called that function, you'd have a resource leak.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top