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

标签 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”的值在调用该函数后发生变化。

最佳答案

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

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

关于c++ - _read 函数返回文件句柄的过时值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18757589/

相关文章:

c++ - SetWindowRgn 阻塞了吗?

.NET 4.0 完整/客户端配置文件;有人关心吗?

msdn - 关于MSDN和商业用途的问题

c++ - 错误 c2065 : 'filename' : undeclared identifier

android - Javac 不会从 .java 创建 native .c 文件。 JNI

c - 与 Supervisord 一起使用非连续程序

c - 是否有返回 bool 的 C 库函数?

c++ - RAII类设计

c++ - 为什么 std::chrono::time_point 的行为不如预期?

c++ - 使用通过模板注入(inject)的模板化类型