【发布时间】:2021-09-07 14:09:00
【问题描述】:
我设置了一个类来读取文件。 将 char * 类型的指针传递给函数,该函数将文件写入指针指向的内存单元。 最后,期待通过函数外的指针读取文件的内容。 但结果并没有达到预期。 在程序内部,有一个结果输出。 但在外面,没有结果。我不知道为什么。
#include <fstream>
#include <stdlib.h>
namespace my
{
class File
{
File() = default;
~File() = default;
bool ReadTo(char * _out, const char * _path);
}
}
bool my::File::ReadTo(char * _out, const char * _path)
{
std::ifstream fs;
//infs lengfsh;
fs.open(_path);
fs.seekg(0, std::ios::end);
long len = fs.tellg();
//goes well at this,output normally
printf("my::File::ReadTo >> len:%d\n",len);
fs.seekg(0, std::ios::beg);
_out = (char *)malloc(sizeof(char) * len);
fs.read(_out, len);
//goes well at this,output normally
printf("my::File::ReadTo >> out:%s\n",_out);
fs.close();
return true;
}
int main()
{
char * txt;
my::File mf;
mf.ReadTo(txt,"x:\\xxxx\\demo.txt");
// result shows : NULL
debug("demo.txt >> \n %s\n",txt);
}
【问题讨论】:
-
你为什么把
ReadTo放在一个无状态的class中?因为它作为一个免费功能会更好。另外,不要使用malloc/free,使用new[]/delete[](如果必须手动管理内存) -
当有更好的方法可以使用 C++ 功能实现目标时,您在 C++ 程序中使用了 C 的许多功能,例如使用
new和delete而不是malloc和 @987654331 @、std::string代替char*、printf代替std::cout << ...。 -
_out必须是char**或char*&。加上main需要根据ReadTo中的内存分配方式来释放指针。更好的解决方案是返回unique_ptr以确保以适当的方式释放内存。或者,my::File中分配的内存可以归类所有,并在其析构函数中释放。您也可以在File中使用std::vector<char>来存储数据。此外,您应该分配一个额外的字节并在其中存储一个 0 以确保任何printf等不会误入未初始化的内存。 -
其实我不太明白什么是“无状态类”。我只是觉得这里使用指针非常灵活,因为文件大小是未知的。在程序之外,我只需要提供一个指针,类中的程序几乎可以做任何事情。
-
Re: “我只是觉得这里使用指针非常灵活,因为文件大小是未知的。” - 可以,但是使用起来也有点困难以安全的方式“拥有数据”的指针。有标准的 C++ 类可以为您工作,例如
std::string和std::vector<char>。