SHFileOperation + string???

alene_cn 2004-12-24 02:33:39
我编写了一段代码,用于删除文件,删除部分如下:

void CClearVCPrjDlg::DeletePrjFiles(const std::string &strFinder)
{
CFileFind finder;
BOOL bWorking = finder.FindFile(strFinder.c_str());

std::string strFile;

while (bWorking)
{
bWorking = finder.FindNextFile();

ASSERT(!finder.IsDots());
ASSERT(!finder.IsDirectory());

strFile = finder.GetFilePath();
//strFile.resize(strFile.length() + 1, 0); <----加了这句SHFileOperation才会返回成功!!!

if (finder.IsReadOnly())
SetFileAttributes(strFile.c_str(), FILE_ATTRIBUTE_NORMAL);

m_sfo.pFrom = strFile.c_str();
if (SHFileOperation(&m_sfo) != 0)
{
finder.Close();

DWORD err = GetLastError();

std::stringstream strmErr;
strmErr << "删除文件(" << strFile << ")失败,错误码(" << err << ")";

MessageBox(strmErr.str().c_str(), "系统提示", MB_OK | MB_ICONERROR);

break;
}
}

finder.Close();
}

上面必须加“strFile.resize(strFile.length() + 1, 0); ”这句,SHFileOperation才会返回成功,否则就失败,错误码为6。这是为什么呢?c_str()返回的是以零为结尾的字符串吗?

如果加了“strFile.resize(strFile.length() + 1, 0); ”,最后的出错信息又会乱掉,例如:

删除文件F:\Temp\test.txt,出错后的提示信息应该为:
“删除文件(F:\Temp\test.txt)失败,错误码(6)”

加了“strFile.resize(strFile.length() + 1, 0); ”之后就变成了
“删除文件(F:\Temp\test.txt”

后面少了一段。

我正在学习C++,想尽量用string代替C风格的字符串,像SHFileOperation出现的这种问题,真是打击我的积极性啊。是不是用了跟API或MFC有关的代码都应该用C风格的字符串或MFC的CString呢?还是我什么地方写得不对?请大家指教。
...全文
107 2 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
alene_cn 2004-12-27
  • 打赏
  • 举报
回复
没有仔细看帮助...

pFrom
Address of a buffer to specify one or more source file names... Each file name must be terminated by a single NULL character. An additional NULL character must be appended to the end of the final name to indicate the end of pFrom
fangrk 2004-12-24
  • 打赏
  • 举报
回复
SHFileOperation好象需要连续两个0结尾的字符串

strFile = finder.GetFilePath();
strFile+=char(0);//这样应该也可以
...

65,187

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧