file_io.cpp 1.65 KB
Newer Older
1
2
/*!
 * Copyright (c) 2018 Microsoft Corporation. All rights reserved.
Guolin Ke's avatar
Guolin Ke committed
3
4
 * Licensed under the MIT License. See LICENSE file in the project root for
 * license information.
5
 */
6
7
8
#include <LightGBM/utils/file_io.h>

#include <LightGBM/utils/log.h>
9
10
11
12

#include <algorithm>
#include <sstream>
#include <unordered_map>
13

14
namespace LightGBM {
15
16

struct LocalFile : VirtualFileReader, VirtualFileWriter {
Guolin Ke's avatar
Guolin Ke committed
17
18
  LocalFile(const std::string& filename, const std::string& mode)
      : filename_(filename), mode_(mode) {}
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
  virtual ~LocalFile() {
    if (file_ != NULL) {
      fclose(file_);
    }
  }

  bool Init() {
    if (file_ == NULL) {
#if _MSC_VER
      fopen_s(&file_, filename_.c_str(), mode_.c_str());
#else
      file_ = fopen(filename_.c_str(), mode_.c_str());
#endif
    }
    return file_ != NULL;
  }

  bool Exists() const {
    LocalFile file(filename_, "rb");
    return file.Init();
  }

  size_t Read(void* buffer, size_t bytes) const {
    return fread(buffer, 1, bytes, file_);
  }

45
  size_t Write(const void* buffer, size_t bytes) {
46
47
48
    return fwrite(buffer, bytes, 1, file_) == 1 ? bytes : 0;
  }

Nikita Titov's avatar
Nikita Titov committed
49
 private:
50
51
52
53
54
  FILE* file_ = NULL;
  const std::string filename_;
  const std::string mode_;
};

Guolin Ke's avatar
Guolin Ke committed
55
56
std::unique_ptr<VirtualFileReader> VirtualFileReader::Make(
    const std::string& filename) {
57
  return std::unique_ptr<VirtualFileReader>(new LocalFile(filename, "rb"));
58
59
}

Guolin Ke's avatar
Guolin Ke committed
60
61
std::unique_ptr<VirtualFileWriter> VirtualFileWriter::Make(
    const std::string& filename) {
62
  return std::unique_ptr<VirtualFileWriter>(new LocalFile(filename, "wb"));
63
64
65
}

bool VirtualFileWriter::Exists(const std::string& filename) {
66
67
  LocalFile file(filename, "rb");
  return file.Exists();
68
69
70
}

}  // namespace LightGBM