How to save winapi file?

Hello, I'm trying to write the file, here's my attempt so far:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
BOOL SaveTextFileFromEdit(HWND hEdit)
{
char buffer[] = "Write this text to file";
	HANDLE hFile;
	BOOL bSuccess = FALSE;

	hFile = CreateFile(pszFileName, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
	if (hFile == INVALID_HANDLE_VALUE)
	{
		MessageBox(NULL, L"Windows failed to save your image", L"Saving Process Failed", MB_ICONERROR);
		return 1;
	}
	else
	{
		DWORD dwTextLength;
		dwTextLength = GetWindowTextLength(hEdit);
		WriteFile(hFile, buffer, sizeof(buffer), &dwTextLength, 0);
		CloseHandle(hFile);
		bSuccess = true;
	}
	return bSuccess;
}


However, I am always getting the error message, any help please?
Last edited on
I suggest that you use GetLastError() to determine why it fails.

Where does pszFileName come from? Maybe the file name/path is invalid.
Have you set pszFileName with the name of the file?

Also if there's an error or not your function always returns TRUE;

1
2
		return 1;
	}

.....
1
2
3
		bSuccess = true;
	}
	return bSuccess;

Here is my file name LPCTSTR pszFileName = L"MyTestFile";

It's a global variable.

Also I fixed the problem Moooce pointed, thanks. But the file still doesn't save for some reason... This is driving me crazy :(
Last edited on
When dealing with the Win API it important to check all return values. There are many things that cn go wrong.
Try this little demo.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
#include <windows.h>
#include <tchar.h>
#include <stdexcept>

#define IDC_EDIT    1000
#define IDC_SAVE    1001

LPCSTR pszFileName = _T("Demo.txt");

TCHAR szClsName[] = _T("BasicApp");
TCHAR szWndName[] = _T("Template");

LRESULT CALLBACK WndProcedure(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam);
ATOM RegisterMyClass();
HWND CreateEditWnd(HWND hWnd, HINSTANCE hInstance);
HWND CreateSaveButton(HWND, HINSTANCE);
void SaveTextFileFromEdit(HWND hEdit);

class Win_error: public std::runtime_error 
{
private:
  std::string m_what;
public:
  Win_error(): std::runtime_error("Windows Error")
  {
    LPVOID lpMsgBuf;
    FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER | 
      FORMAT_MESSAGE_FROM_SYSTEM | 
      FORMAT_MESSAGE_IGNORE_INSERTS,
      NULL, GetLastError(), 0, 
      (LPTSTR) &lpMsgBuf, 0,NULL);
    m_what.assign((const char *)lpMsgBuf);
    LocalFree(lpMsgBuf);
  }
  virtual const char* what()const
  {
    return m_what.c_str();
  }
};

ATOM RegisterMyClass()
{
  WNDCLASSEX WndClsEx;

  WndClsEx.cbSize        = sizeof(WNDCLASSEX);
  WndClsEx.style         = CS_HREDRAW | CS_VREDRAW;
  WndClsEx.lpfnWndProc   = WndProcedure;
  WndClsEx.cbClsExtra    = 0;
  WndClsEx.cbWndExtra    = 0;
  WndClsEx.hIcon         = LoadIcon(NULL, IDI_APPLICATION);
  WndClsEx.hCursor       = LoadCursor(NULL, IDC_ARROW);
  WndClsEx.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
  WndClsEx.lpszMenuName  = NULL;
  WndClsEx.lpszClassName = szClsName;
  WndClsEx.hInstance     = static_cast<HINSTANCE>(::GetModuleHandle(0));
  WndClsEx.hIconSm       = LoadIcon(NULL, IDI_APPLICATION);

  return RegisterClassEx(&WndClsEx);
}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
  MSG        Msg;
  HWND       hWnd;

  if (!RegisterMyClass())
    return FALSE;

  hWnd = CreateWindow(szClsName, szWndName, WS_OVERLAPPEDWINDOW,
    CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, 
    CW_USEDEFAULT, 0, 0, hInstance, 0);                      

  if (!hWnd)
    return FALSE;

  ShowWindow(hWnd, SW_SHOWNORMAL);
  UpdateWindow(hWnd);

  while (GetMessage(&Msg, NULL, 0, 0))
  {
    TranslateMessage(&Msg);
    DispatchMessage(&Msg);
  }

  return (int)Msg.wParam;
}

LRESULT CALLBACK WndProcedure(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam)
{
  HWND hEdit = 0;

  try
  {
    switch (Msg)
    {
    case WM_CREATE:
      CreateEditWnd(hWnd, (HINSTANCE)GetModuleHandle(0));
      CreateSaveButton(hWnd, (HINSTANCE)GetModuleHandle(0));
      break;
    case WM_COMMAND:
      if (LOWORD(wParam) == IDC_SAVE)
      {
        hEdit = GetDlgItem(hWnd, IDC_EDIT);
        if (hEdit == 0)
          throw Win_error();
        SaveTextFileFromEdit(hEdit);
      }
      break;
    case WM_DESTROY:
      PostQuitMessage(0);
      break;
    }
  }
  catch (std::exception& ex)
  {
    MessageBoxA(hWnd, ex.what(), "ERROR", MB_ICONERROR);
  }
  return DefWindowProc(hWnd, Msg, wParam, lParam);
}

HWND CreateEditWnd(HWND hWnd, HINSTANCE hInstance)
{
  DWORD EditStyle = WS_CHILD|WS_VISIBLE|WS_BORDER|ES_MULTILINE;

  HWND hEditWnd = CreateWindowA(_T("EDIT"), 0, EditStyle,
    10, 10, 300, 300, hWnd, (HMENU)IDC_EDIT,  
    hInstance, 0); 

  if (hEditWnd == 0)
    throw Win_error();

  if (SetWindowTextA(hEditWnd, _T("Some demo text\r\nBla Bla Bla")) == 0)
    throw Win_error();


  return hEditWnd;
}

HWND CreateSaveButton(HWND hWnd, HINSTANCE hInstance)
{
  DWORD ButtonStyle = WS_CHILD|WS_VISIBLE;

  HWND hButtonWnd = CreateWindowA(_T("BUTTON"), _T("Save"), ButtonStyle,
    320, 10, 50, 25, hWnd, (HMENU)IDC_SAVE,  
    hInstance, 0); 

  if (hButtonWnd == 0)
    throw Win_error();

  return hButtonWnd;

}

void SaveTextFileFromEdit(HWND hEdit)
{
  HANDLE hFile;
  if(!IsWindow(hEdit))
    throw std::runtime_error("hEdit is invalid");

  hFile = CreateFile(pszFileName, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
  if (hFile == INVALID_HANDLE_VALUE)
    throw Win_error(); 

  DWORD dwTextLength = (DWORD)SendMessageA(hEdit, WM_GETTEXTLENGTH, 0, 0L);
  if (dwTextLength == 0)
    throw std::runtime_error("No text to save");

  std::string buffer(dwTextLength + 1, ' ');
  GetWindowTextA(hEdit, &buffer[0], dwTextLength + 1);
  if(!WriteFile(hFile, &buffer[0], buffer.size(), &dwTextLength, 0))
  {
    CloseHandle(hFile);
    throw Win_error();
  }
  MessageBoxA(0, "Text saved", "SUCCESS", MB_OK);
  CloseHandle(hFile);
}
Topic archived. No new replies allowed.