[英]Turn a C string with NULL bytes into a char array
我正在使用具有多個選擇功能的GetOpenFileName
。 選取的文件以LPSTR返回。 在此LPSTR中,所選文件由NULL字節分隔。 我想將LPSTR拆分成一個數組,然后在該數組上循環。
在PHP中,我會這樣做:
$array = explode("\0", $string);
但是由於我不熟悉C,所以我不知道自己在做什么。
您可以這樣做來遍歷字符串:
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);
如果確實需要,可以修改此代碼以創建數組。
最簡單的操作可能就是直接循環返回的字符串。 (無需創建單獨的數組。)代碼如下所示(省略了錯誤檢查):
GetOpenFileName( &ofn );
LPSTR pszFileName = ofn.lpstrFile;
while( *pszFileName != 0 )
{
// do stuff...
pszFileName += strlen( pszFileName ) + 1;
}
同樣,不要忘記,如果用戶選擇多個文件,則第一個條目將是文件夾名稱。
字符串副本對您有用嗎?
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 */ }
希望這對您有所幫助,湯姆,謝謝。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.