Extract util function to build a local file path

Finding a local file in the scrcpy directory may be useful for files
other than scrcpy-server in the future.
This commit is contained in:
Romain Vimont 2020-12-22 01:15:59 +01:00
parent 230afd8966
commit a7991323e4
3 changed files with 36 additions and 25 deletions

View File

@ -1,6 +1,7 @@
#include "command.h"
#include <assert.h>
#include <libgen.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
@ -229,3 +230,31 @@ process_check_success(process_t proc, const char *name) {
}
return true;
}
char *
get_local_file_path(const char *name) {
char *executable_path = get_executable_path();
if (!executable_path) {
return NULL;
}
char *dir = dirname(executable_path);
size_t dirlen = strlen(dir);
size_t namelen = strlen(name);
size_t len = dirlen + namelen + 2; // +2: '/' and '\0`
char *file_path = SDL_malloc(len);
if (!file_path) {
LOGE("Could not alloc path");
SDL_free(executable_path);
}
memcpy(file_path, dir, dirlen);
file_path[dirlen] = PATH_SEPARATOR;
// namelen + 1 to copy the final '\0'
memcpy(&file_path[dirlen + 1], name, namelen + 1);
SDL_free(executable_path);
return file_path;
}

View File

@ -90,4 +90,9 @@ get_executable_path(void);
bool
is_regular_file(const char *path);
// return the absolute path of a file in the same directory as the executable
// may be NULL on error; to be freed by SDL_free
char *
get_local_file_path(const char *name);
#endif

View File

@ -3,7 +3,6 @@
#include <assert.h>
#include <errno.h>
#include <inttypes.h>
#include <libgen.h>
#include <stdio.h>
#include <SDL2/SDL_thread.h>
#include <SDL2/SDL_timer.h>
@ -53,35 +52,13 @@ get_server_path(void) {
// the absolute path is hardcoded
return server_path;
#else
// use scrcpy-server in the same directory as the executable
char *executable_path = get_executable_path();
if (!executable_path) {
LOGE("Could not get executable path, "
"using " SERVER_FILENAME " from current directory");
// not found, use current directory
return SERVER_FILENAME;
}
char *dir = dirname(executable_path);
size_t dirlen = strlen(dir);
// sizeof(SERVER_FILENAME) gives statically the size including the null byte
size_t len = dirlen + 1 + sizeof(SERVER_FILENAME);
char *server_path = SDL_malloc(len);
char *server_path = get_local_file_path(SERVER_FILENAME);
if (!server_path) {
LOGE("Could not alloc server path string, "
LOGE("Could not get local file path, "
"using " SERVER_FILENAME " from current directory");
SDL_free(executable_path);
return SERVER_FILENAME;
}
memcpy(server_path, dir, dirlen);
server_path[dirlen] = PATH_SEPARATOR;
memcpy(&server_path[dirlen + 1], SERVER_FILENAME, sizeof(SERVER_FILENAME));
// the final null byte has been copied with SERVER_FILENAME
SDL_free(executable_path);
LOGD("Using server (portable): %s", server_path);
return server_path;
#endif