vcpe/srcs/libs/misc/misc.c

152 lines
3.2 KiB
C
Raw Normal View History

2022-05-10 06:43:27 +00:00
//
// Created by xajhu on 2021/7/2 0002.
//
#include <string.h>
#include <uv.h>
#include <sys/vfs.h>
#include <zlog.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/sendfile.h>
#include "user_errno.h"
#include "misc.h"
const char *basename_v2(const char *path) {
const char *tail = strrchr(path, '/');
return tail ? tail + 1 : path;
}
int dirname_v2(const char *path, char *dir) {
const char *tail = strrchr(path, '/');
if (tail) {
memcpy(dir, path, tail - path);
dir[tail - path] = 0;
} else {
strcpy(dir, "./");
}
return 0;
}
unsigned long long get_partition_free_size(const char *pPartPath) {
struct statfs myStatfs;
unsigned long long freeSize;
if (statfs(pPartPath, &myStatfs) == -1) {
return 0;
}
freeSize = myStatfs.f_bsize * myStatfs.f_bfree;
return freeSize;
}
int copy_file(const char *pSrc, const char *pDest) {
int fdSrc, fdDest;
struct stat st;
ssize_t sz;
if (stat(pSrc, &st) != 0) {
dzlog_error("Get File %s Size Error\n", pSrc);
return (-ERR_GET_FILE_SIZE);
}
fdSrc = open(pSrc, O_RDONLY);
if (fdSrc < 0) {
dzlog_error("Open File %s Error\n", pSrc);
return (-ERR_OPEN_FILE);
}
fdDest = open(pDest, O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
if (fdDest < 0) {
close(fdSrc);
dzlog_error("Open File %s Error\n", pDest);
return (-ERR_OPEN_FILE);
}
sz = sendfile(fdDest, fdSrc, NULL, st.st_size);
if (sz != st.st_size) {
dzlog_error("Copy File Size Error: %zd, %ld\n", sz, st.st_size);
close(fdSrc);
close(fdDest);
return (-ERR_COPY_FILE);
}
fsync(fdDest);
close(fdSrc);
close(fdDest);
return (0);
}
char *bin2hex(char *p, const unsigned char *cp, unsigned int count) {
static const char hex_asc[] = "0123456789abcdef";
while (count) {
unsigned char c = *cp++;
/* put lowercase hex digits */
*p++ = (char)(0x20 | hex_asc[c >> 4]);
*p++ = (char)(0x20 | hex_asc[c & 0xf]);
count--;
}
return p;
}
int shell_with_output(const char *pCmd, char **pResult) {
FILE *pFile = NULL;
unsigned int uRdSize;
char *pCmdOut;
*pResult = NULL;
if (pCmd == NULL || strlen(pCmd) == 0) {
return (-ERR_INPUT_PARAMS);
}
pFile = popen(pCmd, "r");
if (pFile == NULL) {
return (-ERR_OPEN_FILE);
}
*pResult = (char *)malloc(4096);
pCmdOut = *pResult;
uRdSize = fread(pCmdOut, sizeof(char), 4096, pFile);
pCmdOut[uRdSize] = 0;
if (pCmdOut[strlen(pCmdOut) - 1] == '\n') {
pCmdOut[strlen(pCmdOut) - 1] = 0;
}
pclose(pFile);
return ERR_OK;
}
int file_exists(const char *pPath) {
if ((access(pPath, F_OK)) == -1) {
return FALSE;
}
return TRUE;
}
const char *get_cur_process_dir() {
static char g_exePath[4096] = {0};
size_t bufSize = 4096L;
if (strlen((const char *)g_exePath) == 0) {
memset(g_exePath, 0, 4096);
uv_cwd(g_exePath, &bufSize);
}
return (const char *)g_exePath;
}