简体   繁体   English

将带有NULL字节的C字符串转换为char数组

[英]Turn a C string with NULL bytes into a char array

I am using GetOpenFileName with multiple select capabilities. 我正在使用具有多个选择功能的GetOpenFileName The files picked are returned in a LPSTR. 选取的文件以LPSTR返回。 Inside this LPSTR, the files selected are separated by NULL bytes. 在此LPSTR中,所选文件由NULL字节分隔。 I want to split the LPSTR into an array and then loop over that array. 我想将LPSTR拆分成一个数组,然后在该数组上循环。

In PHP I would do: 在PHP中,我会这样做:

 $array = explode("\0", $string);

But since I am new to C, I have no idea what I am doing. 但是由于我不熟悉C,所以我不知道自己在做什么。

You could do this to loop through the strings: 您可以这样做来遍历字符串:

char *Buffer;             // your null-separated strings
char *Current;            // Pointer to the current string
// [...]
for (Current = Buffer; *Current; Current += strlen(Current) + 1)
  printf("GetOpenFileName returned: %s\n", Current);

You can adapt this code to create arrays if it's really necessary. 如果确实需要,可以修改此代码以创建数组。

The easiest thing to do is probably just to loop over the returned strings directly. 最简单的操作可能就是直接循环返回的字符串。 (There's no need to create a separate array.) The code would look something like this (error checking omitted): (无需创建单独的数组。)代码如下所示(省略了错误检查):

GetOpenFileName( &ofn );

LPSTR pszFileName = ofn.lpstrFile;

while( *pszFileName != 0 )
{
    // do stuff...
    pszFileName += strlen( pszFileName ) + 1;
}

Also, don't forget that if the user selects multiple files, the first entry will be the folder name. 同样,不要忘记,如果用户选择多个文件,则第一个条目将是文件夹名称。

Would a string copy do the trick for you? 字符串副本对您有用吗?

LPSTR ptrFileName;
char buf[100];
strcpy(buf, ptrFileName);
/* Now iterate */
for (int nLoopCnt = 0; nLoopCnt < (sizeof(buf) / sizeof(buf[0])); nLoopCnt++){
   char ch = buf[nLoopCnt];
   /* Do whatever with ch */
}

Hope this helps, Best regards, Tom. 希望这对您有所帮助,汤姆,谢谢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM