如何以及需要哪些库来在桌面中创建和操作文件?仅使用 C,而不使用 C# 或 C++。 我正在使用Codeblocks,我使用allegro,这意味着我不能使用windows.h lib,该程序需要在windows中运行。
最佳答案
在 Windows Vista 或更高版本中,使用 SHGetKnownFolderPath
查找桌面路径。您必须使用 Unicode 函数来获取文件路径,使用 _wfopen_s
。您可以将 ANSI 写入文件,但建议写入 UTF16 或将文本转换为 UTF8。
#include <stdio.h>
#include <Windows.h>
#include <Shlobj.h>
int main()
{
wchar_t *desktop;
if(S_OK == SHGetKnownFolderPath(&FOLDERID_Desktop, 0, NULL, &desktop))
{
wprintf(L"Desktop path: %s\n", desktop);
wchar_t filename[MAX_PATH];
swprintf_s(filename, MAX_PATH, L"%s\\%s", desktop, L"file.txt");
wprintf(L"Filename path: %s\n", filename);
FILE *fp;
_wfopen_s(&fp, filename, L"w");
if(fp)
{
fprintf(fp, "Hello world\n");
fclose(fp);
}
else
{
wprintf(L"can't create file\n");
}
CoTaskMemFree(desktop);
}
return 0;
}
在 Windows XP 中使用 SHGetSpecialFolderPath
(已弃用)
#include <stdio.h>
#include <Windows.h>
#include <Shlobj.h>
int main()
{
wchar_t desktop[MAX_PATH];
if(SUCCEEDED(SHGetFolderPathW(NULL, CSIDL_DESKTOP | CSIDL_FLAG_CREATE, NULL, 0, desktop)))
{
wprintf(L"desktop: %s\n", desktop);
wchar_t path[MAX_PATH];
swprintf(path, L"%s\\%s", desktop, L"filename.txt");
HANDLE handle = CreateFileW(path, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if(handle != INVALID_HANDLE_VALUE)
{
DWORD temp;
const char *buf = "hello world";
WriteFile(handle, buf, strlen(buf), &temp, NULL);
CloseHandle(handle);
}
else
{
printf("can't create file\n");
}
}
return 0;
}
关于c - 如何使用 c 在桌面上创建文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40814725/