首页 > 解决方案 > 如何在 UWP c++ 中使用 fopen() 打开文件?

问题描述

如何在 UWP 应用程序中打开文件?
我的应用程序将有其他文件(例如文本文件)
我希望我的程序能够访问此文件。那么我该怎么做呢?

标签: c++fileuwp

解决方案


1.) 确保您尝试打开的文件位于应用程序本地文件夹中(文件夹名称“LocalState”)
使用以下代码查找本地文件夹路径。

using namespace Windows::Storage;
using namespace Streams;

textBlock1->Text = ApplicationData::Current->LocalFolder->Path;

这将在文本块名称 textBlock1 中显示本地文件夹路径。

2.) 打开文件名“Sample.txt”

using namespace Windows::Storage;
using namespace Streams;

String^ localfolder = ApplicationData::Current->LocalFolder->Path;
std::wstring basePath(localfolder->Data());
std::wstring fileName(L"\\Sample.txt");
basePath = basePath + fileName;
const wchar_t* fullpath = basePath.c_str();
size_t size = wcslen(fullpath) * 2 + 2;
char * StartPoint = new char[size];
size_t c_size;
wcstombs_s(&c_size, StartPoint, size, fullpath, size);

FILE *fp_testFile = NULL;
errno_t err;

err = fopen_s(&fp_testFile, StartPoint, "rb");
if (err == 0)
{
    OutputDebugStringW(L"opened");
}
else
{
    OutputDebugStringW(L"open failed");
}


字符串转换部分对我来说真的很困惑。
我也不知道如何不手动将文件放在本地文件夹中。
我尝试在解决方案资源管理器 -> 资产下添加文件。但是部署后文件不包含在本地文件夹中


推荐阅读