将“char *”指针传递给函数

Pass a “char *“ pointer to a function

我设置了一个class来读取文件。 将 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);
}

参数 char * _out 将是 已传递内容的副本,因此对其进行修改不会影响已传递内容。

您应该像 char * &_out 那样向它(声明和定义)添加 & 以使其成为一个引用,以便对它的修改将被反射到调用者中指定为参数的内容。

还要确保读取的是 C 风格的字符串(以空字符结尾的字符序列)。换句话说,不要使用不包含任何值为 0x00 的字节的文件来测试您的程序。否则,printf() 将读取超出范围,可能会发生危险。