【问题标题】:close function not being recognized - C++关闭函数未被识别 - C++
【发布时间】:2013-01-12 13:27:35
【问题描述】:

我在名为RaftLog.cc 的文件中有以下代码:

#include <algorithm>
#include <fcntl.h>
#include <sys/stat.h>



namespace LogCabin {
namespace Server {
namespace RaftConsensusInternal {

namespace FilesystemUtil = Storage::FilesystemUtil;

namespace {
bool
fileToProto(const std::string& path, google::protobuf::Message& out)
{
    int fd = open(path.c_str(), O_RDONLY);
    if (fd == -1)
        return false;
    else
        close(fd);
    FilesystemUtil::FileContents file(path);

        // more code down here, not useful to the problem.

但是,当我编译时,我有:

build/Server/RaftLog.cc: In function ‘bool LogCabin::Server::RaftConsensusInternal::{anonymous}::fileToProto(const string&, google::protobuf::Message&)’:
build/Server/RaftLog.cc:43:17: error: ‘close’ was not declared in this scope
build/Server/RaftLog.cc: In function ‘void LogCabin::Server::RaftConsensusInternal::{anonymous}::protoToFile(google::protobuf::Message&, const string&)’:
build/Server/RaftLog.cc:76:13: error: ‘close’ was not declared in this scope
In file included from ./Server/RaftConsensus.h:17:0,

我不知道为什么#include &lt;fcntl.h&gt; 没有包含close() 函数。有人可以帮助我吗?如果我应该包含更多代码,也请告诉我。

【问题讨论】:

    标签: c++ c unix


    【解决方案1】:

    调用close函数需要包含unistd.h头文件

    #include <unistd.h>
    

    使用fopen/fclosefdopen/close

    【讨论】:

    • 仅此而已?我也应该用fclose替换close吗?
    • 仅当您也将 open 替换为 fopen 并重写其余逻辑以使用 FILE*
    • 这突出了我长期存在的一个问题:openfcntl.h 中定义,但它的“相反”closeunistd.h 中定义。我想知道 POSIX 的“基本原理”部分对此有什么看法。
    【解决方案2】:

    在 Visual Studio 2015 中

    #include <corecrt_io.h>
    

    似乎有效!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-25
      相关资源
      最近更新 更多