提问者:小点点

如何在C++中将字符数组转换为文件类型


我是一个C#开发人员,所以我对这种语言有点困惑。 这里的问题是,我正在处理别人的代码,我只需要做一个细微的更改。 我需要将一个接受文件路径参数并使用fopen()将其加载到文件类型的函数更改为一个只接受char数组并将其转换为文件类型的函数

现在的情况是:

bool ExampleFunction::Load(const string& fileName)
{
    string f = filename;


    FILE* fp = fopen(f.c_str(), "rb");
}

我希望它是怎样的(伪代码):

bool ExampleFunction::Load(const char* fileBytes)
{
    FILE* fp = fopen(fileBytes, "rb");
}

共1个答案

匿名用户

您所谓的“伪”代码实际上已经是正确的函数了--除了不返回值之外。 还有一些进一步的提示:

  • 如果将文件指针存储在成员变量中,请检查文件之前是否已打开,并在必要时关闭该文件。
  • 如果只是将一些数据从文件加载到局部变量中,不要忘记在之后再次fclose文件。

否则就会发生内存泄漏。

但是,在原始函数中,您创建了一个完全无用的输入字符串副本:

bool ExampleFunction::Load(const string& fileName)
{
    string f = filename; // <--- copy!!!

    FILE* fp = fopen(f.c_str(), "rb");
}

或者直接使用参数:

FILE* fp = fopen(filename.c_str(), "rb");

或者,如果您想要一个更短的别名,请再次创建它作为引用:

 string const& f = filename;
 // alternatively:
 auto& f = filename;
 //  ^ don't forget, otherwise copy again

我个人建议保留原来的功能作为重载:

bool ExampleFunction::Load(char const* filename);
bool ExampleFunction::Load(std::string const& filename)
{
    return Load(filename.c_str());
}

以便将文件名存储在std::string对象中的用户可以直接使用该文件名。

相关问题


MySQL Query : SELECT * FROM v9_ask_question WHERE 1=1 AND question regexp '(何在|c++|中将|字符|数组|转|换为|文件|类型)' ORDER BY qid DESC LIMIT 20
MySQL Error : Got error 'repetition-operator operand invalid' from regexp
MySQL Errno : 1139
Message : Got error 'repetition-operator operand invalid' from regexp
Need Help?