folder selecting

#include <windows.h>
#include <string>
#include <shlobj.h>
#include <iostream>
#include <sstream>

static int CALLBACK BrowseCallbackProc(HWND hwnd,UINT uMsg, LPARAM lParam, LPARAM lpData)

    if(uMsg == BFFM_INITIALIZED)
        std::string tmp = (const char *) lpData;
        std::cout << "path: " << tmp << std::endl;
        SendMessage(hwnd, BFFM_SETSELECTION, TRUE, lpData);

    return 0;

std::string BrowseFolder(std::string saved_path)
    TCHAR path[MAX_PATH];

    const char * path_param = saved_path.c_str();

    BROWSEINFO bi = { 0 };
    bi.lpszTitle  = ("Browse for folder...");
    bi.lpfn       = BrowseCallbackProc;
    bi.lParam     = (LPARAM) path_param;

    LPITEMIDLIST pidl = SHBrowseForFolder ( &bi );

    if ( pidl != 0 )
        //get the name of the folder and put it in path
        SHGetPathFromIDList ( pidl, path );

        //free memory used
        IMalloc * imalloc = 0;
        if ( SUCCEEDED( SHGetMalloc ( &imalloc )) )
            imalloc->Free ( pidl );
            imalloc->Release ( );

        return path;

    return "";

int main(int argc, const char *argv[])
    std::string path = BrowseFolder(argv[1]);
    std::cout << path << std::endl;
    return 0;

The Common File Dialogs

The first step to opening or saving files is finding out the filename to use… of course you could always hard code the name of the file into your program, but honestly that doesn’t make for very useful programs most of the time.

Since this is such a common task, there are predefined system dialogs that you can use to allow the user to select a file name. The most common open and save file dialogs are accessed through GetOpenFileName() andGetSaveFileName() respectively, both of which take an OPENFILENAME struct.

    char szFileName[MAX_PATH] = "";

    ZeroMemory(&ofn, sizeof(ofn));

    ofn.lStructSize = sizeof(ofn); // SEE NOTE BELOW
    ofn.hwndOwner = hwnd;
    ofn.lpstrFilter = "Text Files (*.txt)\0*.txt\0All Files (*.*)\0*.*\0";
    ofn.lpstrFile = szFileName;
    ofn.nMaxFile = MAX_PATH;
    ofn.lpstrDefExt = "txt";

        // Do something usefull with the filename stored in szFileName 

Note that we call ZeroMemory() on the struct in order to initialise it to 0. This is generally a wise practice, as some APIs are very picky about members that you don’t use being set to NULL. This way you don’t need to explicitely set each member that you don’t use.

You can easily find out the meanings of the various members by looking them up in your documentation. The lpstrFilter value points to a double-NULL terminated string, and you can see from the example that there are several "\0" throughout it, including one at the end… the compiler will add the second one at the end as it always does with string constants (that’s what you generally don’t need to put them in yourself). The NULLs in this string break it up into filters, each one is two parts. The first filter has the description "Text Files (*.txt)", the wildcard isn’t required here I just put it in because I felt like it. The next part is the actual wildcard for the first filter, "*.txt". We do the same thing with the second filter except that this is a generic filter for all files. You can add as many different filters as you’d like.

The lpstrFile points to the buffer we have allocated to store the name of the file, since filenames can’t be larger than MAX_PATH this is the value that I’ve chosen for the buffer size.

The flags indicate that the dialog should only allow the user to enter filenames that already exist (since we want to open them, not create them) and to hide the option to open the file in readonly mode, which we aren’t going to support. Finally we provide a default extention, so if the user types in "foo" and the file is not found, it will try to open "foo.txt" before finally giving up.

To select a file for saving instead of opening, the code is nearly the same, except for calling GetSaveFileName() we need only change the flags member to options more suitable for saving.


In this case we no longer want to require the file exist, but we do want the directory to exist since we aren’t going to try and create it first. We’ll also prompt the user if they select an existing file to make sure they want to overwrite it.

NOTE: MSDN States the following for the lStructSize member:

Specifies the length, in bytes, of the structure.Windows NT 4.0: In an application that is compiled with WINVER and _WIN32_WINNT >= 0x0500, use OPENFILENAME_SIZE_VERSION_400 for this member.

Windows 2000/XP: Use sizeof (OPENFILENAME) for this parameter.

Basically what this means is that as of Windows 2000 they added some members to this struct, and so it’s size changed. If the code above doesn’t work for you it’s possibly because the size that your compiler used and the size that your operating system (ie. Windows 98, Windows NT4) expected were different and so the call failed. If this happens, try using OPENFILENAME_SIZE_VERSION_400 instead of sizeof(ofn). Thanks to people that pointed this out to me.

Reading and Writing Files

In windows you have a few options as to how you want to access files. You can use the old io.h open()/read()/write(), you can use stdio.hfopen()/fread()/fwrite(), and if you are in C++ use can use iostreams.

However in windows all of these method ultimately call the Win32 API functions, which are what I will use here. If you are already comfortable using file IO with another method it should be fairly easy to pick up, or if you want simply use your method of choice to access files.

To open files, you can use OpenFile() or CreateFile(). MS recommends using only CreateFile() as OpenFile() is now “obsolete”. CreateFile() is a much more versatile function and provides a great deal of control over the way you open files.


Say for example you have allowed the user to select a file using GetOpenFileName()…

BOOL LoadTextFileToEdit(HWND hEdit, LPCTSTR pszFileName)
    HANDLE hFile;
    BOOL bSuccess = FALSE;

    hFile = CreateFile(pszFileName, GENERIC_READ, FILE_SHARE_READ, NULL,
        OPEN_EXISTING, 0, NULL);
        DWORD dwFileSize;

        dwFileSize = GetFileSize(hFile, NULL);
        if(dwFileSize != 0xFFFFFFFF)
            LPSTR pszFileText;

            pszFileText = GlobalAlloc(GPTR, dwFileSize + 1);
            if(pszFileText != NULL)
                DWORD dwRead;

                if(ReadFile(hFile, pszFileText, dwFileSize, &dwRead, NULL))
                    pszFileText[dwFileSize] = 0; // Add null terminator
                    if(SetWindowText(hEdit, pszFileText))
                        bSuccess = TRUE; // It worked!
    return bSuccess;

There is a complete function to read a text file into an edit control. It takes as paramters the handle to the edit control and the name of the file to read in. This perticular function has a fair bit of error checking, file IO is one place where a lot of things can go wrong, and so you need to be on the lookout for errors.

Note the variable dwRead. We don’t use it except as a paramter in ReadFile(). This parameter MUST be provided, the call will fail without it.

In the call to CreateFile() GENERIC_READ means we only want read access. FILE_SHARE_READ means it’s okay if other programs open the file at the same time we do, but ONLY if they want to read as well, we don’t want them writing to the file while we are reading it. And OPEN_EXISTING means only open the file if it already exists, don’t create it, and don’t overwrite it.

Once we’ve opened the file and chacked to see that CreateFile() succeeded, we check the size of the file so we’ll know how much memory we need to allocate in order to read the entire thing. We then allocate the memory, check to make sure the allocation succeeded, and then call ReadFile() to load the contents from disk into our memory buffer. The API file functions have no concept of Text Files so they won’t do things like read a single line of text, or add NULL terminators to the end of our strings. This is why we’ve allocated an extra byte and after we read in the file we add the NULL ourselves so that we can then pass the memory buffer as a string to SetWindowText().

Once all that has succeeded we set out success variable to TRUE, and clean up as we reach the end of the function, freeing the memory buffer and closing the file handle before finally returning to the caller.


BOOL SaveTextFileFromEdit(HWND hEdit, LPCTSTR pszFileName)
    HANDLE hFile;
    BOOL bSuccess = FALSE;

    hFile = CreateFile(pszFileName, GENERIC_WRITE, 0, NULL,
        DWORD dwTextLength;

        dwTextLength = GetWindowTextLength(hEdit);
        // No need to bother if there's no text.
        if(dwTextLength > 0)
            LPSTR pszText;
            DWORD dwBufferSize = dwTextLength + 1;

            pszText = GlobalAlloc(GPTR, dwBufferSize);
            if(pszText != NULL)
                if(GetWindowText(hEdit, pszText, dwBufferSize))
                    DWORD dwWritten;

                    if(WriteFile(hFile, pszText, dwTextLength, &dwWritten, NULL))
                        bSuccess = TRUE;
    return bSuccess;

Very similar to reading files, the function to write files has a few changes. First of all when we call CreateFile() we specify that we want Read access, that the file should always be created new (and if it exists it will be erased as it’s opened) and that if it doesn’t exist, it will be created with the normal file attributes.

Next we get the length of the memory buffer needed from the edit control, since this is the source of the data. Once we’ve allocated the memory, we request the string from the edit control using GetWindowText() and then write it to the file with WriteFile(). Again, like with ReadFile() the parameter that returns how much was actually written is required, even though we don’t use it.

A simple GetOpenFileName example

  1. #include "stdafx.h"
  2. #include <windows.h>
  3. #include "resource.h"
  4. #include <Commdlg.h>
  5. //
  6. // Gobal Variables and declarations.
  7. //
  9. // a another memory buffer to contain the file name
  10. char szFile[100] ;
  11. int WINAPI WinMain( HINSTANCE hInstance , HINSTANCE hPrevInstance , LPSTR lpCmdLine , int nCmdShow )
  12. {
  13. // open a file name
  14. ZeroMemory( &ofn , sizeof( ofn));
  15. ofn.lStructSize = sizeof ( ofn );
  16. ofn.hwndOwner = NULL ;
  17. ofn.lpstrFile = szFile ;
  18. ofn.lpstrFile[0] = '\0';
  19. ofn.nMaxFile = sizeof( szFile );
  20. ofn.lpstrFilter = "All\0*.*\0Text\0*.TXT\0";
  21. ofn.nFilterIndex =1;
  22. ofn.lpstrFileTitle = NULL ;
  23. ofn.nMaxFileTitle = 0 ;
  24. ofn.lpstrInitialDir=NULL ;
  26. GetOpenFileName( &ofn );
  27. // Now simpley display the file name
  28. MessageBox ( NULL , ofn.lpstrFile , "File Name" , MB_OK);
  29. return 0;
  30. }

create a modal dialog box using win32 APIs

#include <windows.h>

BITMAP   bmp;

void PaintBkBitmap(HWND hWndDlg) {

    HDC      hdc, hMemDC;


    HGDIOBJ hOld;

    RECT rc;


    hdc = BeginPaint(hWndDlg,&ps);

    hMemDC = CreateCompatibleDC(hdc);

    hOld = SelectObject(hMemDC,hBitmap);

    BOOL bRet = BitBlt(hdc,rc.right - 50 - 200,10,200,87,hMemDC,0,0,SRCAND);






LRESULT CALLBACK DlgProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);

int APIENTRY WinMain(HINSTANCE hInstance,

                     HINSTANCE hPrevInstance,

                     LPTSTR    lpCmdLine,

                     int       nCmdShow)




    hInst = hInstance;

    int nRet = (int)DialogBox(hInst,MAKEINTRESOURCE(IDD_DIALOG),0,(DLGPROC) DlgProc);

    if (-1 == nRet)


      return FALSE;


    return 0;


BOOL       DlgCmd   (   HWND    hwndDlg,        // handle to dialog box

                        UINT    uMsg,           // message

                        WPARAM  wParam,         // first message parameter

                        LPARAM  lParam          // second message parameter

                    ) {

    WORD    wNotifyCode;

    WORD    wID;

    HWND    hwndCtl;

    wNotifyCode =   HIWORD(wParam); // notification code 

    wID         =   LOWORD(wParam); // item, control, or accelerator identifier 

    hwndCtl     =   (HWND) lParam;  // handle of control 

    if  (BN_CLICKED ==  wNotifyCode) {  //  nothing else will happen...



                case    IDC_OK:

                            return DlgOK(hwndDlg);


                case    IDC_CANCEL:






    return( TRUE);


BOOL DlgOK(HWND hwndDlg) {

    return TRUE;


BOOL DlgInit(HWND hwndDlg) {

    hBitmap = LoadBitmap(hInst,MAKEINTRESOURCE(IDB_BITMAP));

    int nRet = GetObject(hBitmap, sizeof(BITMAP), (LPVOID)&bmp);


    return TRUE;



     switch (uMsg) {

                case    WM_INITDIALOG:  return  (   DlgInit   (   hwndDlg));

                case    WM_COMMAND:     return  (   DlgCmd    (   hwndDlg,






                case    WM_PAINT:       PaintBkBitmap( hwndDlg);


    return FALSE;


Select all

A Free Day

Loading … loading … and loading :(. The internet has some problems. haizz. Long time until now, I have a day… free day. Actually I don’t know how should I do now. Recently, turtle is quiet busy … I can’t understand what is he doing ??? @@ before I enter this site I had a lot of things in my head but … when I see the screen, it’s seem disappear. A 🙂 now, I just think I am not a gentle girl, I’m a shrewd maybe ??? :)) I don’t know all above sentence, how many true sentences or fall but you get my thinkings, right ? Hic you must because you obligated me write by english 😉 A day for silly thoughts

Goodnight Turtle

a simple http uploader

url =
file = local file path
file2 = filename for upload
submit_name = the name of the submit html field on the page
submit_value = the value for the submit field
file_form_name = the file name field on the html page
mime_type = the http file type of the upload
folder_path = the path including file of the page to upload to ie: /pictures/user/index.php
int UpLoad( const char *url, const char *file, const char *file2, const char *submit_name, const char *submit_value, 
const char *file_form_name, const char *mime_type, const char *folder_path )
    WSADATA wsaData;
    WSAStartup( MAKEWORD( 2,2 ), &wsaData );

    if( sock == INVALID_SOCKET )
        return 0;

    int value = 5000;
    if( setsockopt( sock, SOL_SOCKET, SO_SNDTIMEO, (char *)&value, sizeof( int ) ) == SOCKET_ERROR )
        closesocket( sock );
        return 0;
    LPHOSTENT hostEntry;
    hostEntry = gethostbyname( url );

    if( hostEntry == NULL )
        closesocket( sock );
        return 0;
    sockaddr_in addr2;
    addr2.sin_family = AF_INET;
    addr2.sin_addr = *((LPIN_ADDR)*hostEntry->h_addr_list);
    addr2.sin_port = htons( 80 );
    if( connect( sock, (LPSOCKADDR) &addr2, sizeof(struct sockaddr) ) == SOCKET_ERROR )
        closesocket( sock );
        return 0;


    if( !f )
        closesocket( sock );
        return 0;

    char end[512] = "";
    wsprintf( end, "\r\n-----------------------------3164130335698\r\nContent-Disposition: form-data; name=\"%s\"\r\n\r\n%s\r\n-----------------------------3164130335698\r\n\r\n", submit_name, submit_value );

    DWORD hi;
    DWORD size = GetFileSize( f, &hi );

    char *filepart = (char *) GlobalAlloc( GPTR, size + 2048 );

    wsprintf( filepart, "-----------------------------3164130335698\r\nContent-Disposition: form-data; name=\"%s\"; filename=\"%s\"\r\nContent-Type: %s\r\n\r\n", file_form_name, file, mime_type );

    DWORD len = strlen( filepart );

    ReadFile( f, (LPVOID)((DWORD)filepart + len), size, &hi, NULL );

    CloseHandle( f );

    char *request = (char *) GlobalAlloc( GPTR, 1024 + len + size + 1 );

    wsprintf( request, 
    "POST /%s HTTP/1.1\r\nHost: %s\r\nUser-Agent: ELUpload/1.0\r\nConnection: Keep-alive\r\nContent-Type: multipart/form-data; boundary=---------------------------3164130335698\r\nContent-length: %d\r\n---------------------------3164130335698\r\nContent-Disposition: form-data; name=\"MAX_FILE_SIZE\"\r\n\r\n100000\r\n", 
    folder_path, url, len + size + 1 + strlen( end ) );
    DWORD head = strlen( request );

    memcpy( request + head, filepart, len + size + 1 );
    head += len + size + 1;
    memcpy( request + head, end, strlen( end ) );
    head += strlen( end );
    for( int i = 0; i < head; i++ )
        if( send( sock, (request + i), 1, 0 ) == SOCKET_ERROR )
            closesocket( sock );
            GlobalFree( request );
            GlobalFree( filepart );
            return 0;

    closesocket( sock );

    GlobalFree( request );
    GlobalFree( filepart );
    return 1;
<form enctype="multipart/form-data" action="upload.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
Choose a file to upload: <input name="uploadedfile" type="file" /><br />
<input type="text" name="serial"><br>
<input type="submit" name="submit" value="Upload File" />

giữa đêm không tìm đến giấc ngủ

Đã nhiều lúc tôi vốn nghĩ cuộc đời này bất công, cùng với điều đó tôi mang theo những hận thù , căm ghét trút lên những gì tối thấy hoặc không may mắn lọt vào suy nghĩ của tôi. Chao ôi tôi đã sai nhiều lần không đếm nỗi và lần này cũng vậy. vừa mở mắt thì nghe tin máy bay rơi. vừa ngồi xuống nghỉ ngơi thì hay tin xe gặp tai nạn, biết bao đau thương , mất mát đến với nhiều người mà chỉ một phút thoáng qua tôi không dừng được cảm xúc của mình có những lúc muốn bật khóc như nếm được mùi đau đớn. Tôi của hiện tại dám tự nhận mình nếm trái đắng sao? đau khổ kia tôi nếm phải có là gì so với những người hôm nay tôi thấy, ngày hôm qua tôi được nghe kể lại? Tôi thật còn may mắn lắm thế tại sao lại tự mang đến phiền muồn và tuôn hận thù. Tôi thật có lỗi.


Thanks for all

Một cái tên có thể đổi, một đường link cũng có thể thay đổi… đúng không… có thể biến mất như nó chưa từng tồn tại. Một ngày đã qua, là một ngày như thế nào  rùi  nhỉ . E vốn chẳng tin vào ngôn tình mà nếu nó có thật thì e cũng sẽ chẳng phải là người may mắn ấy đâu đúng không. Có lẽ đây là lần cuối rồi. Thật sự muốn nghe 1 lời chúc từ a, một lời chúc như những lúc a vẫn hát vui nhưng chắc là không được rồi.Thêm một tuổi ùi chắc e sẽ cố không trẻ con nữa, không bị bắt nạt nữa . E không biết hiện giờ mình đang nghĩ gì nữa E nhớ e từng hỏi nếu như 1 ngày e biến mất thì a có sao không. Dĩ nhiên là không sao rồi, điều đó e cũng tự hiểu mà.  Dù sao e cũng cảm ơn a thời gian qua đã chấp nhận cho 1 đứa dở hơi như e làm phiền đủ kiểu. Có lẽ với a chỉ vui thôi nhưng với e điều đó thật tốt biết bao. Chắc a cũng chẳng quan tâm tại sao hay chuyện gì đâu. Mà thật ra cũng chẳng có chuyện gì cả . Sau này chúc a luôn vui vẻ, hanh phúc sẽ luôn đến với a. Cảm ơn anh vì tất cả .

Best things will come to you