io.cpp 9.5 KB
Newer Older
羽飞's avatar
羽飞 已提交
1
/* Copyright (c) 2021 OceanBase and/or its affiliates. All rights reserved.
羽飞's avatar
羽飞 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
miniob is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:
         http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details. */

//
// Created by Longda on 2010
//

#include <dirent.h>
#include <iostream>
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

#include "common/io/io.h"
#include "common/lang/string.h"
#include "common/log/log.h"
#include "common/math/regex.h"
#include "common/mm/mem.h"

namespace common {

30 31
int readFromFile(const std::string &fileName, char *&outputData, size_t &fileSize)
{
羽飞's avatar
羽飞 已提交
32 33
  FILE *file = fopen(fileName.c_str(), "rb");
  if (file == NULL) {
34
    std::cerr << "Failed to open file " << fileName << SYS_OUTPUT_FILE_POS << SYS_OUTPUT_ERROR << std::endl;
羽飞's avatar
羽飞 已提交
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
    return -1;
  }

  // fseek( file, 0, SEEK_END );
  // size_t fsSize = ftell( file );
  // fseek( file, 0, SEEK_SET );

  char buffer[4 * ONE_KILO];
  size_t readSize = 0;
  size_t oneRead = 0;

  char *data = NULL;
  do {
    memset(buffer, 0, sizeof(buffer));
    oneRead = fread(buffer, 1, sizeof(buffer), file);
    if (ferror(file)) {
51
      std::cerr << "Failed to read data" << fileName << SYS_OUTPUT_FILE_POS << SYS_OUTPUT_ERROR << std::endl;
羽飞's avatar
羽飞 已提交
52 53 54 55 56 57 58 59 60 61
      fclose(file);
      if (data != NULL) {
        lfree(data);
        data = NULL;
      }
      return -1;
    }

    data = (char *)lrealloc(data, readSize + oneRead);
    if (data == NULL) {
62
      std::cerr << "Failed to alloc memory for " << fileName << SYS_OUTPUT_FILE_POS << SYS_OUTPUT_ERROR << std::endl;
羽飞's avatar
羽飞 已提交
63 64 65 66 67 68 69 70 71 72 73 74
      lfree(data);
      fclose(file);
      return -1;
    } else {
      memcpy(data + readSize, buffer, oneRead);
      readSize += oneRead;
    }

  } while (feof(file) == 0);

  fclose(file);

Y
Yu Dou 已提交
75 76
  data = (char *)lrealloc(data, readSize + 1);
  data[readSize] = '\0';
羽飞's avatar
羽飞 已提交
77 78 79 80 81
  outputData = data;
  fileSize = readSize;
  return 0;
}

羽飞's avatar
羽飞 已提交
82
int writeToFile(const std::string &fileName, const char *data, uint32_t dataSize, const char *openMode)
83
{
羽飞's avatar
羽飞 已提交
84 85
  FILE *file = fopen(fileName.c_str(), openMode);
  if (file == NULL) {
86
    std::cerr << "Failed to open file " << fileName << SYS_OUTPUT_FILE_POS << SYS_OUTPUT_ERROR << std::endl;
羽飞's avatar
羽飞 已提交
87 88 89
    return -1;
  }

羽飞's avatar
羽飞 已提交
90
  uint32_t leftSize = dataSize;
羽飞's avatar
羽飞 已提交
91 92 93 94
  const char *buffer = data;
  while (leftSize > 0) {
    int writeCount = fwrite(buffer, 1, leftSize, file);
    if (writeCount <= 0) {
95
      std::cerr << "Failed to open file " << fileName << SYS_OUTPUT_FILE_POS << SYS_OUTPUT_ERROR << std::endl;
羽飞's avatar
羽飞 已提交
96 97 98 99 100 101 102 103 104 105 106 107 108
      fclose(file);
      return -1;
    } else {
      leftSize -= writeCount;
      buffer += writeCount;
    }
  }

  fclose(file);

  return 0;
}

羽飞's avatar
羽飞 已提交
109
int getFileLines(const std::string &fileName, uint64_t &lineNum)
110
{
羽飞's avatar
羽飞 已提交
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
  lineNum = 0;

  char line[4 * ONE_KILO] = {0};

  std::ifstream ifs(fileName.c_str());
  if (!ifs) {
    return -1;
  }

  while (ifs.good()) {
    line[0] = 0;
    ifs.getline(line, sizeof(line));
    char *lineStrip = strip(line);
    if (strlen(lineStrip)) {
      lineNum++;
    }
  }

  ifs.close();
  return 0;
}

羽飞's avatar
羽飞 已提交
133
int getFileNum(int64_t &fileNum, const std::string &path, const std::string &pattern, bool recursive)
134
{
羽飞's avatar
羽飞 已提交
135 136 137 138
  try {
    DIR *dirp = NULL;
    dirp = opendir(path.c_str());
    if (dirp == NULL) {
139
      std::cerr << "Failed to opendir " << path << SYS_OUTPUT_FILE_POS << SYS_OUTPUT_ERROR << std::endl;
羽飞's avatar
羽飞 已提交
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
      return -1;
    }

    std::string fullPath;
    struct dirent *entry = NULL;
    struct stat fs;
    while ((entry = readdir(dirp)) != NULL) {
      // don't care ".", "..", ".****" hidden files
      if (!strncmp(entry->d_name, ".", 1)) {
        continue;
      }

      fullPath = path;
      if (path[path.size() - 1] != FILE_PATH_SPLIT) {
        fullPath += FILE_PATH_SPLIT;
      }
      fullPath += entry->d_name;
      memset(&fs, 0, sizeof(fs));
      if (stat(fullPath.c_str(), &fs) < 0) {
159
        std::cout << "Failed to stat " << fullPath << SYS_OUTPUT_FILE_POS << SYS_OUTPUT_ERROR << std::endl;
羽飞's avatar
羽飞 已提交
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
        continue;
      }

      if (fs.st_mode & S_IFDIR) {
        if (recursive == 0) {
          continue;
        }

        if (getFileNum(fileNum, fullPath, pattern, recursive) < 0) {
          closedir(dirp);
          return -1;
        }
      }

      if (!(fs.st_mode & S_IFREG)) {
        // not regular files
        continue;
      }

179
      if (pattern.empty() == false && regex_match(entry->d_name, pattern.c_str())) {
羽飞's avatar
羽飞 已提交
180 181 182 183 184 185 186 187 188 189 190
        // Don't match
        continue;
      }

      fileNum++;
    }

    closedir(dirp);

    return 0;
  } catch (...) {
191
    std::cerr << "Failed to get file num " << path << SYS_OUTPUT_FILE_POS << SYS_OUTPUT_ERROR << std::endl;
羽飞's avatar
羽飞 已提交
192 193 194 195
  }
  return -1;
}

196 197
int getFileList(std::vector<std::string> &fileList, const std::string &path, const std::string &pattern, bool recursive)
{
羽飞's avatar
羽飞 已提交
198 199 200 201
  try {
    DIR *dirp = NULL;
    dirp = opendir(path.c_str());
    if (dirp == NULL) {
202
      std::cerr << "Failed to opendir " << path << SYS_OUTPUT_FILE_POS << SYS_OUTPUT_ERROR << std::endl;
羽飞's avatar
羽飞 已提交
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
      return -1;
    }

    std::string fullPath;
    struct dirent *entry = NULL;
    struct stat fs;
    while ((entry = readdir(dirp)) != NULL) {
      // don't care ".", "..", ".****" hidden files
      if (!strncmp(entry->d_name, ".", 1)) {
        continue;
      }

      fullPath = path;
      if (path[path.size() - 1] != FILE_PATH_SPLIT) {
        fullPath += FILE_PATH_SPLIT;
      }
      fullPath += entry->d_name;
      memset(&fs, 0, sizeof(fs));
      if (stat(fullPath.c_str(), &fs) < 0) {
222
        std::cout << "Failed to stat " << fullPath << SYS_OUTPUT_FILE_POS << SYS_OUTPUT_ERROR << std::endl;
羽飞's avatar
羽飞 已提交
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
        continue;
      }

      if (fs.st_mode & S_IFDIR) {
        if (recursive == 0) {
          continue;
        }

        if (getFileList(fileList, fullPath, pattern, recursive) < 0) {
          closedir(dirp);
          return -1;
        }
      }

      if (!(fs.st_mode & S_IFREG)) {
        // regular files
        continue;
      }

242
      if (pattern.empty() == false && regex_match(entry->d_name, pattern.c_str())) {
羽飞's avatar
羽飞 已提交
243 244 245 246 247 248 249 250 251 252
        // Don't match
        continue;
      }

      fileList.push_back(fullPath);
    }

    closedir(dirp);
    return 0;
  } catch (...) {
253
    std::cerr << "Failed to get file list " << path << SYS_OUTPUT_FILE_POS << SYS_OUTPUT_ERROR << std::endl;
羽飞's avatar
羽飞 已提交
254 255 256 257
  }
  return -1;
}

258 259
int getDirList(std::vector<std::string> &dirList, const std::string &path, const std::string &pattern)
{
羽飞's avatar
羽飞 已提交
260 261 262 263
  try {
    DIR *dirp = NULL;
    dirp = opendir(path.c_str());
    if (dirp == NULL) {
264
      std::cerr << "Failed to opendir " << path << SYS_OUTPUT_FILE_POS << SYS_OUTPUT_ERROR << std::endl;
羽飞's avatar
羽飞 已提交
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
      return -1;
    }

    std::string fullPath;
    struct dirent *entry = NULL;
    struct stat fs;
    while ((entry = readdir(dirp)) != NULL) {
      // don't care ".", "..", ".****" hidden files
      if (!strncmp(entry->d_name, ".", 1)) {
        continue;
      }

      fullPath = path;
      if (path[path.size() - 1] != FILE_PATH_SPLIT) {
        fullPath += FILE_PATH_SPLIT;
      }
      fullPath += entry->d_name;
      memset(&fs, 0, sizeof(fs));
      if (stat(fullPath.c_str(), &fs) < 0) {
284
        std::cout << "Failed to stat " << fullPath << SYS_OUTPUT_FILE_POS << SYS_OUTPUT_ERROR << std::endl;
羽飞's avatar
羽飞 已提交
285 286 287 288 289 290 291
        continue;
      }

      if ((fs.st_mode & S_IFDIR) == 0) {
        continue;
      }

292
      if (pattern.empty() == false && regex_match(entry->d_name, pattern.c_str())) {
羽飞's avatar
羽飞 已提交
293 294 295 296 297 298 299 300 301 302
        // Don't match
        continue;
      }

      dirList.push_back(fullPath);
    }

    closedir(dirp);
    return 0;
  } catch (...) {
303
    std::cerr << "Failed to get file list " << path << SYS_OUTPUT_FILE_POS << SYS_OUTPUT_ERROR << std::endl;
羽飞's avatar
羽飞 已提交
304 305 306 307
  }
  return -1;
}

308 309 310 311
int touch(const std::string &path)
{
  // CWE367: A check occurs on a file's attributes before
  // the file is used in a privileged operation, but things
羽飞's avatar
羽飞 已提交
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
  // may have changed

  // struct stat fs;

  // memset(&fs, 0, sizeof(fs));
  // if (stat(path.c_str(), &fs) == 0) {
  //   return 0;
  // }

  // create the file
  FILE *file = fopen(path.c_str(), "a");
  if (file == NULL) {
    return -1;
  }
  fclose(file);
  return 0;
}

羽飞's avatar
羽飞 已提交
330
int getFileSize(const char *filePath, int64_t &fileLen)
331
{
羽飞's avatar
羽飞 已提交
332 333 334 335 336 337 338 339 340
  if (filePath == NULL || *filePath == '\0') {
    std::cerr << "invalid filepath" << std::endl;
    return -EINVAL;
  }
  struct stat statBuf;
  memset(&statBuf, 0, sizeof(statBuf));

  int rc = stat(filePath, &statBuf);
  if (rc) {
341
    std::cerr << "Failed to get stat of " << filePath << "," << errno << ":" << strerror(errno) << std::endl;
羽飞's avatar
羽飞 已提交
342 343 344 345 346 347 348 349 350 351 352 353
    return rc;
  }

  if (S_ISDIR(statBuf.st_mode)) {
    std::cerr << filePath << " is directory " << std::endl;
    return -EINVAL;
  }

  fileLen = statBuf.st_size;
  return 0;
}

羽飞's avatar
羽飞 已提交
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390
int writen(int fd, const void *buf, int size)
{
  const char *tmp = (const char *)buf;
  while ( size > 0) {
    const ssize_t ret = ::write(fd, tmp, size);
    if (ret >= 0) {
      tmp  += ret;
      size -= ret;
      continue;
    }
    const int err = errno;
    if (EAGAIN != err && EINTR != err)
      return err;
   }
  return 0;
}

int readn(int fd, void *buf, int size)
{
  char *tmp = (char *)buf;
  while (size > 0) {
    const ssize_t ret = ::read(fd, tmp, size);
    if (ret > 0) {
      tmp  += ret;
      size -= ret;
      continue;
    }
    if (0 == ret)
      return -1; // end of file

    const int err = errno;
    if (EAGAIN != err && EINTR != err)
      return err;
  }
  return 0;
}
}  // namespace common