我是一个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");
}
您所谓的“伪”代码实际上已经是正确的函数了--除了不返回值之外。 还有一些进一步的提示:
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
对象中的用户可以直接使用该文件名。