1
1
Fork 0
mirror of https://github.com/QB64-Phoenix-Edition/QB64pe.git synced 2024-07-06 19:50:22 +00:00

Simplify func__cwd()

This commit is contained in:
Samuel Gomes 2023-12-10 12:25:38 +05:30
parent 7a1f5100f2
commit 96a2ffcb1e

View file

@ -1,3 +1,7 @@
//----------------------------------------------------------------------------------------------------
// QB64-PE filesystem related functions
//-----------------------------------------------------------------------------------------------------
#include "libqb-common.h" #include "libqb-common.h"
#include "filepath.h" #include "filepath.h"
@ -5,57 +9,45 @@
#include "../../libqb.h" #include "../../libqb.h"
#ifdef QB64_WINDOWS
# define __GetCWD _getcwd
#else
# define __GetCWD getcwd
#endif
// Get Current Working Directory // Get Current Working Directory
qbs *func__cwd() { qbs *func__cwd() {
qbs *final, *tqbs; qbs *final;
int length; size_t size = FILENAME_MAX;
char *buf, *ret; auto buffer = (char *)malloc(size);
if (!buffer)
goto error_handler;
#if defined QB64_WINDOWS for (;;) {
length = GetCurrentDirectoryA(0, NULL); if (__GetCWD(buffer, size)) {
buf = (char *)malloc(length); size = strlen(buffer);
if (!buf) { final = qbs_new(size, 1);
error(7); //"Out of memory" memcpy(final->chr, buffer, size);
return tqbs; free(buffer);
} return final;
if (GetCurrentDirectoryA(length, buf) != --length) { // Sanity check } else {
free(buf); // It's good practice free(buffer);
tqbs = qbs_new(0, 1); if (errno == ERANGE) {
error(51); //"Internal error" // Buffer size was not sufficient; try again with a larger buffer
return tqbs; size <<= 1;
} buffer = (char *)malloc(size);
#elif defined QB64_UNIX if (!buffer)
length = 512; goto error_handler;
while (1) { } else {
buf = (char *)malloc(length); // Some other error occurred
if (!buf) { goto error_handler;
tqbs = qbs_new(0, 1); }
error(7);
return tqbs;
} }
ret = getcwd(buf, length);
if (ret)
break;
if (errno != ERANGE) {
tqbs = qbs_new(0, 1);
error(51);
return tqbs;
}
free(buf);
length += 512;
} }
length = strlen(ret);
ret = (char *)realloc(ret, length); // Chops off the null byte error_handler:
if (!ret) { final = qbs_new(0, 1);
tqbs = qbs_new(0, 1); error(7);
error(7);
return tqbs;
}
buf = ret;
#endif
final = qbs_new(length, 1);
memcpy(final->chr, buf, length);
free(buf);
return final; return final;
} }