我设置了一个类来读取文件。 将 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);
}
答案 0 :(得分:2)
参数 char * _out
将是传递的内容的副本,因此修改它不会影响传递的内容。
您应该将 &
添加到它(声明和定义),如 char * &_out
以使其成为引用,以便对其的修改将反映到调用者中指定为参数的内容。>
还要确保读取的是 C 样式字符串(以空字符结尾的字符序列)。换句话说,不要使用不包含任何值为 0x00 的字节的文件来测试您的程序。否则,printf()
的读数将超出范围,可能会发生危险的事情。