_read函数返回文件句柄的过时值

时间:2013-09-12 07:05:24

标签: c++ c msdn

此处的代码块运行良好,直到调用_read函数,之后它无缘无故地更改文件句柄变量'fh'的值。

    std::string& xLogFile;
    std::string& xBuffer;
    struct _stat& xStatBuffer)

char *buffer;
buffer = (char *)malloc(sizeof(char) * xStatBuffer.st_size);
#define _O_RDONLY       0x0000  /* open for reading only */

int fh = 0, read_bytes =0;
fh = _open(xLogFile.c_str(), _O_RDONLY);  // ToDo function deprecated should be changed to fstream

if (fh ==1)
{
    if (mWriteLog) IntPkgUtil::TraceLog("Error!! Couldn't open the log file");
    return true;
}

read_bytes = _read(fh,&buffer,xStatBuffer.st_size);

_close(fh);
if (read_bytes <= 0)
{
    if (mWriteLog) IntPkgUtil::TraceLog("Error!! Couldn't read the log file");
    return true;
}
buffer[read_bytes] = '\0';
xBuffer = buffer;

这是我用来从文件读入缓冲区的代码块,但它在_read函数失败,其中文件句柄'fh'的值在调用函数后发生了变化。

1 个答案:

答案 0 :(得分:1)

修复如下代码,缓冲区而不是&amp;缓冲区。你正在覆盖堆栈。

read_bytes = _read(fh,buffer,xStatBuffer.st_size);