8

为了使用 SHFileOperation,我需要将字符串格式化为双空终止字符串。

有趣的部分是我发现以下工作之一,但不是两者兼而有之:

  // Example 1
  CString szDir(_T("D:\\Test"));
  szDir = szDir + _T('\0') + _T('\0');

  // Example 2  
  CString szDir(_T("D:\\Test"));
  szDir = szDir + _T("\0\0");

  //Delete folder
  SHFILEOPSTRUCT fileop;
  fileop.hwnd   = NULL;    // no status display
  fileop.wFunc  = FO_DELETE;  // delete operation
  fileop.pFrom  = szDir;  // source file name as double null terminated string
  fileop.pTo    = NULL;    // no destination needed
  fileop.fFlags = FOF_NOCONFIRMATION|FOF_SILENT;  // do not prompt the user
  fileop.fAnyOperationsAborted = FALSE;
  fileop.lpszProgressTitle     = NULL;
  fileop.hNameMappings         = NULL;
  int ret = SHFileOperation(&fileop);

有人对此有想法吗?

还有其他方法可以附加双终止字符串吗?

4

2 回答 2

9

CString 类本身对包含空字符的字符串没有问题。问题在于首先将空字符放入字符串中。第一个示例有效,因为它附加的是单个字符,而不是字符串 - 它按原样接受字符,而不检查它是否为空。第二个示例尝试附加一个典型的 C 字符串,根据定义,该字符串在第一个空字符处结束 - 您实际上是在附加一个空字符串。

于 2011-01-06T05:50:30.937 回答
6

您不能CString用于此目的。您将需要使用自己的char[]缓冲区:

char buf[100]; // or large enough
strcpy(buf, "string to use");
memcpy(buf + strlen(buf), "\0\0", 2);

虽然您可以通过在现有 NUL 终止符之后再复制一个 NUL 字节来做到这一点,但我更愿意复制两个,以便源代码更准确地反映程序员的意图。

于 2011-01-06T02:35:47.350 回答