filesystem: SDL_GetCurrentDirectory() should add a path separator at the end.

This commit is contained in:
Ryan C. Gordon 2025-01-15 17:06:09 -05:00
parent 87e1b0eb89
commit eb793dede7
3 changed files with 21 additions and 4 deletions

View file

@ -483,6 +483,9 @@ extern SDL_DECLSPEC char ** SDLCALL SDL_GlobDirectory(const char *path, const ch
* platforms without this concept, this would cause surprises with file access * platforms without this concept, this would cause surprises with file access
* outside of SDL. * outside of SDL.
* *
* The returned path is guaranteed to end with a path separator ('\\' on
* Windows, '/' on most other platforms).
*
* \returns a UTF-8 string of the current working directory in * \returns a UTF-8 string of the current working directory in
* platform-dependent notation. NULL if there's a problem. This * platform-dependent notation. NULL if there's a problem. This
* should be freed with SDL_free() when it is no longer needed. * should be freed with SDL_free() when it is no longer needed.

View file

@ -217,7 +217,7 @@ char *SDL_SYS_GetCurrentDirectory(void)
} }
buf = (char *) ptr; buf = (char *) ptr;
if (getcwd(buf, buflen) != NULL) { if (getcwd(buf, buflen-1) != NULL) {
break; // we got it! break; // we got it!
} }
@ -231,6 +231,14 @@ char *SDL_SYS_GetCurrentDirectory(void)
return NULL; return NULL;
} }
// make sure there's a path separator at the end.
SDL_assert(SDL_strlen(buf) < (buflen + 2));
buflen = SDL_strlen(buf);
if ((buflen == 0) || (buf[buflen-1] != '/')) {
buf[buflen] = '/';
buf[buflen + 1] = '\0';
}
return buf; return buf;
} }

View file

@ -355,11 +355,17 @@ char *SDL_SYS_GetCurrentDirectory(void)
if (bw == 0) { if (bw == 0) {
WIN_SetError("GetCurrentDirectoryW failed"); WIN_SetError("GetCurrentDirectoryW failed");
return NULL; return NULL;
} else if (bw < buflen) { } else if (bw < buflen) { // we got it!
break; // we got it! // make sure there's a path separator at the end.
SDL_assert(bw < (buflen + 2));
if ((bw == 0) || (wstr[bw-1] != '\\')) {
wstr[bw] = '\\';
wstr[bw + 1] = '\0';
}
break;
} }
void *ptr = SDL_realloc(wstr, bw * sizeof (WCHAR)); void *ptr = SDL_realloc(wstr, (bw + 1) * sizeof (WCHAR));
if (!ptr) { if (!ptr) {
SDL_free(wstr); SDL_free(wstr);
return NULL; return NULL;