00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015 #include "base/filelinereader.h"
00016
00017 #include <string.h>
00018 #include <string>
00019
00020 #include "base/file.h"
00021 #include "base/logging.h"
00022 #include "base/scoped_ptr.h"
00023
00024 namespace operations_research {
00025 FileLineReader::FileLineReader(const char* const filename)
00026 : filename_(filename), line_callback_(NULL), loaded_successfully_(false) {}
00027
00028 FileLineReader::~FileLineReader() {}
00029
00030 void FileLineReader::set_line_callback(Callback1<char*>* const callback) {
00031 line_callback_.reset(callback);
00032 }
00033
00034 void FileLineReader::Reload() {
00035 const int kMaxLineLength = 60 * 1024;
00036 File* const data_file = File::Open(filename_, "r");
00037 if (data_file == NULL) {
00038 loaded_successfully_ = false;
00039 return;
00040 }
00041
00042 scoped_array<char> line(new char[kMaxLineLength]);
00043 for (;;) {
00044 char* const result = data_file->ReadLine(line.get(), kMaxLineLength);
00045 if (result == NULL) {
00046 data_file->Close();
00047 loaded_successfully_ = true;
00048 return;
00049 }
00050
00051 int len = strlen(result);
00052 if (len > 0 && result[len - 1] == '\n') {
00053 result[--len] = '\0';
00054 }
00055 if (len > 0 && result[len - 1] == '\r') {
00056 result[--len] = '\0';
00057 }
00058 if (line_callback_.get() != NULL) {
00059 line_callback_->Run(result);
00060 }
00061 }
00062 }
00063
00064 bool FileLineReader::loaded_successfully() const {
00065 return loaded_successfully_;
00066 }
00067 }