1
1
Fork 0
mirror of https://github.com/QB64-Phoenix-Edition/QB64pe.git synced 2024-07-04 04: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 "filepath.h"
@ -5,57 +9,45 @@
#include "../../libqb.h"
#ifdef QB64_WINDOWS
# define __GetCWD _getcwd
#else
# define __GetCWD getcwd
#endif
// Get Current Working Directory
qbs *func__cwd() {
qbs *final, *tqbs;
int length;
char *buf, *ret;
qbs *final;
size_t size = FILENAME_MAX;
auto buffer = (char *)malloc(size);
if (!buffer)
goto error_handler;
#if defined QB64_WINDOWS
length = GetCurrentDirectoryA(0, NULL);
buf = (char *)malloc(length);
if (!buf) {
error(7); //"Out of memory"
return tqbs;
}
if (GetCurrentDirectoryA(length, buf) != --length) { // Sanity check
free(buf); // It's good practice
tqbs = qbs_new(0, 1);
error(51); //"Internal error"
return tqbs;
}
#elif defined QB64_UNIX
length = 512;
while (1) {
buf = (char *)malloc(length);
if (!buf) {
tqbs = qbs_new(0, 1);
error(7);
return tqbs;
for (;;) {
if (__GetCWD(buffer, size)) {
size = strlen(buffer);
final = qbs_new(size, 1);
memcpy(final->chr, buffer, size);
free(buffer);
return final;
} else {
free(buffer);
if (errno == ERANGE) {
// Buffer size was not sufficient; try again with a larger buffer
size <<= 1;
buffer = (char *)malloc(size);
if (!buffer)
goto error_handler;
} else {
// Some other error occurred
goto error_handler;
}
}
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
if (!ret) {
tqbs = qbs_new(0, 1);
error(7);
return tqbs;
}
buf = ret;
#endif
final = qbs_new(length, 1);
memcpy(final->chr, buf, length);
free(buf);
error_handler:
final = qbs_new(0, 1);
error(7);
return final;
}