tags:

views:

334

answers:

3

I am using GetOpenFileName with multiple select capabilities. The files picked are returned in a LPSTR. Inside this LPSTR, the files selected are separated by NULL bytes. I want to split the LPSTR into an array and then loop over that array.

In PHP I would do:

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

But since I am new to C, I have no idea what I am doing.

+3  A: 

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.

Samuel_xL
Note that this will only work if the LPSTR ends in *two* null characters. Otherwise, it will continue to print out chunks of memory until it happens to run into two consecutive bytes equal to zero, or until it causes a segfault.
e.James
That's true, but the buffer is indeed double-null terminated. See GetOpenFileName in MSDN.
Peter Ruderman
this is the only method that worked for me. thank you.
Ramblingwood
+1  A: 

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.

tommieb75
+3  A: 

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.

Peter Ruderman
That doesn't work. It gives me an error about '+=' not able to do a left hand assignment.
Ramblingwood