7/02/2008

07-02-08 - 1

There's an annoying quirk with the system stat() call that I haven't seen documented. I'm not sure if this is an MS quirk or more global :

stat() on most dirs will fail if you stick on a trailing slash, eg. stat("c:\windows\") is no good, you must stat("c:\windows");

However :

stat() on the root dir of a drive will fail if it DOESN'T have a trailing slash. eg. stat("c:\") is good but stat("c:") is not.

So, you can make your own stat() wrapper that removes the trailing slash if strlen is > 3. I guess you should probably also look for len 2 drive root specs and add a slash.

Hmmm .. Jon pointed out this is bad on Xbox 360 since I'm relying on drive names being 1 letter. You can do the same thing without explicit lengths by working off the colon; ending with a ":" is bad, ending with ":\" is good, otherwise ending with "\" is bad.

int __cdecl mystat (const char *spec, struct _stat *st)
{
	size_t len = strlen(spec);
	if ( len == 0 )
	{
		return -1;
	}
	else if ( spec[len-1] == ':' )
	{3
		// add trailing slash :
		char * temp = (char *) _alloca(len+1);
		memcpy(temp,spec,len);
		temp[len] = '\\';
		temp[len+1] = 0;
		
		return ::_stat(temp,st);
	}
	else if ( spec[len-1] == '\\' && len > 1 && spec[len-2] != ':' )
	{
		// kill trailing slash :
		char * temp = (char *) _alloca(len);
		memcpy(temp,spec,len);
		temp[len-1] = 0;
		
		return ::_stat(temp,st);
	}
	else
	{
		return ::_stat(spec,st);
	}
}

BTW there is a bit of ambiguity if somebody tries to stat something like "c:" - did they mean the root, or did they mean the current dir on c drive in that DOS way of tracking current dirs on each drive?

No comments:

old rants