io.cpp 9.4 KB
Newer Older
羽飞's avatar
羽飞 已提交
1 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
/* Copyright (c) 2021 Xie Meiyi(xiemeiyi@hust.edu.cn) and OceanBase and/or its affiliates. All rights reserved.
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 75 76 77 78 79
      lfree(data);
      fclose(file);
      return -1;
    } else {
      memcpy(data + readSize, buffer, oneRead);
      readSize += oneRead;
    }

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

  fclose(file);

  outputData = data;
  fileSize = readSize;
  return 0;
}

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

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

  fclose(file);

  return 0;
}

107 108
int getFileLines(const std::string &fileName, u64_t &lineNum)
{
羽飞's avatar
羽飞 已提交
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
  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;
}

131 132
int getFileNum(u64_t &fileNum, const std::string &path, const std::string &pattern, bool recursive)
{
羽飞's avatar
羽飞 已提交
133 134 135 136
  try {
    DIR *dirp = NULL;
    dirp = opendir(path.c_str());
    if (dirp == NULL) {
137
      std::cerr << "Failed to opendir " << path << SYS_OUTPUT_FILE_POS << SYS_OUTPUT_ERROR << std::endl;
羽飞's avatar
羽飞 已提交
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
      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) {
157
        std::cout << "Failed to stat " << fullPath << SYS_OUTPUT_FILE_POS << SYS_OUTPUT_ERROR << std::endl;
羽飞's avatar
羽飞 已提交
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
        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;
      }

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

      fileNum++;
    }

    closedir(dirp);

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

194 195
int getFileList(std::vector<std::string> &fileList, const std::string &path, const std::string &pattern, bool recursive)
{
羽飞's avatar
羽飞 已提交
196 197 198 199
  try {
    DIR *dirp = NULL;
    dirp = opendir(path.c_str());
    if (dirp == NULL) {
200
      std::cerr << "Failed to opendir " << path << SYS_OUTPUT_FILE_POS << SYS_OUTPUT_ERROR << std::endl;
羽飞's avatar
羽飞 已提交
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
      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) {
220
        std::cout << "Failed to stat " << fullPath << SYS_OUTPUT_FILE_POS << SYS_OUTPUT_ERROR << std::endl;
羽飞's avatar
羽飞 已提交
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
        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;
      }

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

      fileList.push_back(fullPath);
    }

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

256 257
int getDirList(std::vector<std::string> &dirList, const std::string &path, const std::string &pattern)
{
羽飞's avatar
羽飞 已提交
258 259 260 261
  try {
    DIR *dirp = NULL;
    dirp = opendir(path.c_str());
    if (dirp == NULL) {
262
      std::cerr << "Failed to opendir " << path << SYS_OUTPUT_FILE_POS << SYS_OUTPUT_ERROR << std::endl;
羽飞's avatar
羽飞 已提交
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
      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) {
282
        std::cout << "Failed to stat " << fullPath << SYS_OUTPUT_FILE_POS << SYS_OUTPUT_ERROR << std::endl;
羽飞's avatar
羽飞 已提交
283 284 285 286 287 288 289
        continue;
      }

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

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

      dirList.push_back(fullPath);
    }

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

306 307 308 309
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
羽飞 已提交
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
  // 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;
}

328 329
int getFileSize(const char *filePath, u64_t &fileLen)
{
羽飞's avatar
羽飞 已提交
330 331 332 333 334 335 336 337 338
  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) {
339
    std::cerr << "Failed to get stat of " << filePath << "," << errno << ":" << strerror(errno) << std::endl;
羽飞's avatar
羽飞 已提交
340 341 342 343 344 345 346 347 348 349 350 351
    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
羽飞 已提交
352 353 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
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