bool FileCreator::setFileSize()

in util/FileCreator.cpp [19:51]


bool FileCreator::setFileSize(ThreadCtx &threadCtx, int fd, int64_t fileSize) {
  struct stat fileStat;
  if (fstat(fd, &fileStat) != 0) {
    WPLOG(ERROR) << "fstat() failed for " << fd;
    return false;
  }
  if (fileStat.st_size > fileSize) {
    // existing file is larger than required
    int64_t sizeToTruncate =
        (threadCtx.getOptions().shouldPreallocateFiles() ? fileSize : 0);
    if (ftruncate(fd, sizeToTruncate) != 0) {
      WPLOG(ERROR) << "ftruncate() failed for " << fd << " " << sizeToTruncate;
      return false;
    }
  }
  if (fileSize == 0) {
    return true;
  }
  if (!threadCtx.getOptions().shouldPreallocateFiles()) {
    // pre-allocation is disabled
    return true;
  }
#ifdef HAS_POSIX_FALLOCATE
  int status = posix_fallocate(fd, 0, fileSize);
  if (status != 0) {
    WLOG(ERROR) << "fallocate() failed " << strerrorStr(status);
    return false;
  }
  return true;
#else
  WDT_CHECK(false) << "Should never reach here";
#endif
}