【问题标题】:_read function is returning obsolete values for file handle_read 函数正在返回文件句柄的过时值
【发布时间】:2013-09-12 07:05:23
【问题描述】:

这里的代码块运行良好,直到调用_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”的值在调用该函数后发生变化。

【问题讨论】:

  • 你不需要在buffer前面加上&amp; - 那是把数据读错地方了。

标签: c++ c msdn


【解决方案1】:

修复如下代码,buffer而不是&buffer。您正在覆盖堆栈。

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

【讨论】:

  • 谢谢,这个改变很有帮助,但是使用 buffer 和 &buffer 对我的事业有什么帮助?
  • 'buffer' 指向分配的内存。然而 &buffer 是指针变量 'buffer' 的地址。
猜你喜欢
  • 1970-01-01
  • 2023-04-03
  • 1970-01-01
  • 2016-07-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多