kythe.io@v0.0.68-0.20240422202219-7225dbc01741/kythe/cxx/common/file_utils.cc (about)

     1  /*
     2   * Copyright 2019 The Kythe Authors. All rights reserved.
     3   *
     4   * Licensed under the Apache License, Version 2.0 (the "License");
     5   * you may not use this file except in compliance with the License.
     6   * You may obtain a copy of the License at
     7   *
     8   *   http://www.apache.org/licenses/LICENSE-2.0
     9   *
    10   * Unless required by applicable law or agreed to in writing, software
    11   * distributed under the License is distributed on an "AS IS" BASIS,
    12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13   * See the License for the specific language governing permissions and
    14   * limitations under the License.
    15   */
    16  
    17  #include "file_utils.h"
    18  
    19  #include <cstdio>
    20  #include <string>
    21  
    22  #include "absl/log/check.h"
    23  
    24  namespace kythe {
    25  
    26  std::string LoadFileOrDie(const std::string& file) {
    27    FILE* handle = fopen(file.c_str(), "rb");
    28    CHECK(handle != nullptr) << "Couldn't open input file " << file;
    29    CHECK_EQ(fseek(handle, 0, SEEK_END), 0) << "Couldn't seek " << file;
    30    long size = ftell(handle);  // NOLINT(google-runtime-int): ftell is defined to
    31                                // return `long`.
    32    CHECK_GE(size, 0) << "Bad size for " << file;
    33    CHECK_EQ(fseek(handle, 0, SEEK_SET), 0) << "Couldn't seek " << file;
    34    std::string content;
    35    content.resize(size);
    36    CHECK_EQ(fread(&content[0], size, 1, handle), 1) << "Couldn't read " << file;
    37    CHECK_NE(fclose(handle), EOF) << "Couldn't close " << file;
    38    return content;
    39  }
    40  
    41  }  // namespace kythe