本人菜鸟一只,写了一个读入全部文件的函数,接口一直有问题,代码如下:
int ReadAllFile(wstring sfilepath, WCHAR*sfile,int mod)
{
wifstream file(sfilepath.c_str(), std::wifstream::binary);
WCHAR*szencr;
if (file)
{
// Calculate the file's size, and allocate a buffer of that size.
file.seekg(0, file.end);
const int file_size = file.tellg();
if (file_size > (1024 * 10000))
{
file.close();
//delete szencr;
return -1;
}
// Read the entire file into the buffer.
file.seekg(0, file.beg);
szencr = new WCHAR[file_size + 1];
memset(szencr, 0, file_size + 1);
//szencr = file.rdbuf();
file.read(szencr, file_size);
//file.getline(szencr, file_size);
file.close();
sfile = szencr;//希望传出地址
return 0;
}
else
{
return -1;
}
}
但是这样出来的sfile 一直为null,一直以为sfile 就是个地址,我传的地址进去,就应该能带出地址,实际上是不行的,应该将参数改成如下:
int CSkfControl::ReadAllFile(wstring sfilepath, WCHAR*&sfile,int mod)//引用传递,不是引用的话,值传递,一直不知道指针也是可以引用传递的。。。。。太菜了
{
wifstream file(sfilepath.c_str(), std::wifstream::binary);
WCHAR*szencr;
if (file)
{
// Calculate the file's size, and allocate a buffer of that size.
file.seekg(0, file.end);
const int file_size = file.tellg();
if (file_size > (1024 * 10000))
{
file.close();
//delete szencr;
return -1;
}
// Read the entire file into the buffer.
file.seekg(0, file.beg);
szencr = new WCHAR[file_size + 1];
memset(szencr, 0, file_size + 1);
//szencr = file.rdbuf();
file.read(szencr, file_size);
//file.getline(szencr, file_size);
file.close();
sfile = szencr;
return 0;
}
else
{
return -1;
}
}