github.com/igggame/nebulas-go@v2.1.0+incompatible/nf/nvm/v8/lib/file.cc (about) 1 // Copyright (C) 2017 go-nebulas authors 2 // 3 // This file is part of the go-nebulas library. 4 // 5 // the go-nebulas library is free software: you can redistribute it and/or 6 // modify it under the terms of the GNU General Public License as published by 7 // the Free Software Foundation, either version 3 of the License, or 8 // (at your option) any later version. 9 // 10 // the go-nebulas library is distributed in the hope that it will be useful, 11 // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 // GNU General Public License for more details. 14 // 15 // You should have received a copy of the GNU General Public License 16 // along with the go-nebulas library. If not, see 17 // <http://www.gnu.org/licenses/>. 18 // 19 20 #include "file.h" 21 #include "logger.h" 22 #include <errno.h> 23 #include <stdio.h> 24 #include <stdlib.h> 25 #include <string.h> 26 #include <sys/stat.h> 27 #include <unistd.h> 28 29 char *readFile(const char *filepath, size_t *size) { 30 if (size != NULL) { 31 *size = 0; 32 } 33 34 FILE *f = fopen(filepath, "r"); 35 if (f == NULL) { 36 return NULL; 37 } 38 39 // get file size. 40 fseek(f, 0L, SEEK_END); 41 size_t file_size = ftell(f); 42 rewind(f); 43 44 char *data = (char *)malloc(file_size + 1); 45 size_t idx = 0; 46 47 size_t len = 0; 48 while ((len = fread(data + idx, sizeof(char), file_size + 1 - idx, f)) > 0) { 49 idx += len; 50 } 51 *(data + idx) = '\0'; 52 53 if (feof(f) == 0) { 54 free(static_cast<void *>(data)); 55 return NULL; 56 } 57 58 fclose(f); 59 60 if (size != NULL) { 61 *size = file_size; 62 } 63 64 return data; 65 } 66 67 bool isFile(const char *file) { 68 struct stat buf; 69 if (stat(file, &buf) != 0) { 70 return false; 71 } 72 if (S_ISREG(buf.st_mode)) { 73 return true; 74 } else { 75 return false; 76 } 77 } 78 79 bool getCurAbsolute(char *curCwd, int len) { 80 char tmp[MAX_VERSIONED_PATH_LEN] = {0}; 81 if (!getcwd(tmp, MAX_VERSIONED_PATH_LEN)) { 82 return false; 83 } 84 85 strncat(tmp, "/lib/1.0.0/execution_env.js", MAX_VERSIONED_PATH_LEN - strlen(tmp) - 1); 86 87 char *pc = realpath(tmp, NULL); 88 if (pc == NULL) { 89 return false; 90 } 91 int pcLen = strlen(pc); 92 if (pcLen >= len) { 93 free(pc); 94 return false; 95 } 96 memcpy(curCwd, pc, pcLen - strlen("/1.0.0/execution_env.js")); 97 //strncpy(curCwd, pc, len - 1); 98 curCwd[pcLen - strlen("/1.0.0/execution_env.js")] = 0x00; 99 free(pc); 100 return true; 101 }