//#define _GNU_SOURCE // for canonicalize_file_name #include #include #include #include #include #include #include "fileutil.h" ///////////////////////////////////////////////////////////////////////////// size_t GetFileSize(FILE *fd) { long nRet = 0; long nCur = ftell(fd); if(!fseek(fd, 0, SEEK_END)) { if((nRet = ftell(fd)) < 0) nRet = 0; fseek(fd, nCur, SEEK_SET); } return (size_t)nRet; } ///////////////////////////////////////////////////////////////////////////// int FileExist(const char *file) { if(!file || !*file) return 0; struct stat s; memset(&s, 0, sizeof(s)); return !stat(file, &s) && S_ISREG(s.st_mode); } ///////////////////////////////////////////////////////////////////////////// int DirectoryExist(const char *dir) { if(!dir || !*dir) return 0; struct stat s; memset(&s, 0, sizeof(s)); return !stat(dir, &s) && S_ISDIR(s.st_mode); } ///////////////////////////////////////////////////////////////////////////// // creates a directory with read/write/search permissions for owner and group, // and with read/search permissions for others int CreateDirectory(const char *pszDir) { if(mkdir(pszDir, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) < 0) { if(errno != EEXIST) return 0; } return 1; } ///////////////////////////////////////////////////////////////////////////// const char* GetAppPath(char *pszPath, size_t nCChPath) { char szTmp[32]; if(!pszPath || !nCChPath) { errno = EINVAL; return NULL; } sprintf(szTmp, "/proc/%d/exe", getpid()); ssize_t nLen = readlink(szTmp, pszPath, nCChPath - 1); if(nLen < 0) { *pszPath = '\0'; return NULL; } pszPath[nLen] = '\0'; return pszPath; } ///////////////////////////////////////////////////////////////////////////// const char* GetAppDirectory(char *pszDir, size_t nCChDir) { char *pszSl; if(!GetAppPath(pszDir, nCChDir)) return NULL; if((pszSl = strrchr(pszDir, '/'))) { if(pszSl != pszDir) *pszSl = '\0'; else *(pszSl + 1) = '\0'; } return pszDir; } ///////////////////////////////////////////////////////////////////////////// const char* BuildCanonicalFilePath(const char *pszDir, const char *pszFilespec, char *pszPath, size_t nCChPath) { size_t nLen; char szDir[PATH_MAX]; char *pszCanPath, szFilePath[PATH_MAX]; if(!pszFilespec || !*pszFilespec || !pszPath || !nCChPath) { errno = EINVAL; return NULL; } if(!pszDir) { memset(szDir, 0, sizeof(szDir)); if(!GetAppDirectory(szDir, sizeof(szDir))) return NULL; pszDir = szDir; } snprintf(szFilePath, sizeof(szFilePath), "%s/%s", pszDir, pszFilespec); if(!(pszCanPath = canonicalize_file_name(szFilePath))) return NULL; nLen = strlen(pszCanPath); if(nLen < nCChPath) strcpy(pszPath, pszCanPath); else { errno = ENOMEM; pszPath = NULL; } free(pszCanPath); return pszPath; }