FreeRDP
TestFileCreateFile.c
1 
2 #include <stdio.h>
3 #include <winpr/crt.h>
4 #include <winpr/file.h>
5 #include <winpr/path.h>
6 #include <winpr/handle.h>
7 #include <winpr/windows.h>
8 #include <winpr/sysinfo.h>
9 
10 int TestFileCreateFile(int argc, char* argv[])
11 {
12  HANDLE handle = NULL;
13  HRESULT hr = 0;
14  DWORD written = 0;
15  const char buffer[] = "Some random text\r\njust want it done.";
16  char cmp[sizeof(buffer)];
17  char sname[8192];
18  LPSTR name = NULL;
19  int rc = 0;
20  SYSTEMTIME systemTime;
21  WINPR_UNUSED(argc);
22  WINPR_UNUSED(argv);
23  GetSystemTime(&systemTime);
24  (void)sprintf_s(sname, sizeof(sname),
25  "CreateFile-%04" PRIu16 "%02" PRIu16 "%02" PRIu16 "%02" PRIu16 "%02" PRIu16
26  "%02" PRIu16 "%04" PRIu16,
27  systemTime.wYear, systemTime.wMonth, systemTime.wDay, systemTime.wHour,
28  systemTime.wMinute, systemTime.wSecond, systemTime.wMilliseconds);
29  name = GetKnownSubPath(KNOWN_PATH_TEMP, sname);
30 
31  if (!name)
32  return -1;
33 
34  /* On windows we would need '\\' or '/' as seperator.
35  * Single '\' do not work. */
36  hr = PathCchConvertStyleA(name, strlen(name), PATH_STYLE_UNIX);
37 
38  if (FAILED(hr))
39  rc = -1;
40 
41  handle = CreateFileA(name, GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_NEW,
42  FILE_ATTRIBUTE_NORMAL, NULL);
43 
44  if (!handle)
45  {
46  free(name);
47  return -1;
48  }
49 
50  if (!winpr_PathFileExists(name))
51  rc = -1;
52 
53  if (!WriteFile(handle, buffer, sizeof(buffer), &written, NULL))
54  rc = -1;
55 
56  if (written != sizeof(buffer))
57  rc = -1;
58 
59  written = SetFilePointer(handle, 5, NULL, FILE_BEGIN);
60 
61  if (written != 5)
62  rc = -1;
63 
64  written = SetFilePointer(handle, 0, NULL, FILE_CURRENT);
65 
66  if (written != 5)
67  rc = -1;
68 
69  written = SetFilePointer(handle, -5, NULL, FILE_CURRENT);
70 
71  if (written != 0)
72  rc = -1;
73 
74  if (!ReadFile(handle, cmp, sizeof(cmp), &written, NULL))
75  rc = -1;
76 
77  if (written != sizeof(cmp))
78  rc = -1;
79 
80  if (memcmp(buffer, cmp, sizeof(buffer)) != 0)
81  rc = -1;
82 
83  if (!CloseHandle(handle))
84  rc = -1;
85 
86  if (!winpr_DeleteFile(name))
87  rc = -1;
88 
89  if (winpr_PathFileExists(name))
90  rc = -1;
91 
92  free(name);
93  return rc;
94 }