ReadFile lpBuffer parameter
ReadFile lpBuffer parameter
我正在使用ReadFile读取一个简单字符串,该字符串是我使用WriteFile写入文件的。
有一个简单的字符串:"测试字符串,测试窗口函数"。
使用WriteFile将其写入文件。
现在我想使用ReadFile来确认它是否已写入该文件。我需要将我读到的内容与上面的原始字符串进行比较。要从文件中读取,我有
DWORD dwBytesRead;
char buff[128];
if(!ReadFile(hFile, buff, 128, &dwBytesRead, NULL))
//Fail
函数返回true,因此它正在从文件中读取。问题是buff充满了正义感。我以前从未遇到过LPVOID,所以我不知道它是不是有什么东西。有什么方法可以进行字符串比较吗?
编辑:我用来写入文件的代码很简单:
if(!WriteFile(hFile, sentence.c_str(), sentence.length(), &bytesWritten, NULL))
{
//FAIL
}
文件指针需要在WriteFile()
之后和ReadFile()
之前重新缠绕。目前,ReadFile()
没有失败,但读取零字节,因此buff
保持不变。由于buff
未初始化,因此它包含垃圾。要将文件指针倒带到文件的开头,请使用SetFilePointer()
:
#include <windows.h>
#include <iostream>
#include <string>
int main()
{
HANDLE hFile = CreateFile ("myfile.txt",
GENERIC_WRITE | GENERIC_READ,
0,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL);
if (hFile)
{
std::string sentence("a test");
DWORD bytesWritten;
if (WriteFile(hFile,
sentence.c_str(),
sentence.length(),
&bytesWritten,
NULL))
{
if (INVALID_SET_FILE_POINTER != SetFilePointer(hFile,
0,
0,
FILE_BEGIN))
{
char buf[128] = { 0 }; /* Initialise 'buf'. */
DWORD bytesRead;
/* Read one less char into 'buf' to ensure null termination. */
if (ReadFile(hFile, buf, 127, &bytesRead, NULL))
{
std::cout << "[" << buf << "]n";
}
else
{
std::cerr << "Failed to ReadFile: " <<
GetLastError() << "n";
}
}
else
{
std::cerr << "Failed to SetFilePointer: " <<
GetLastError() << "n";
}
}
else
{
std::cerr << "Failed to WriteFile: " << GetLastError() << "n";
}
CloseHandle(hFile);
}
else
{
std::cerr << "Failed to open file: " << GetLastError() << "n";
}
return 0;
}
函数返回true,因此它正在从文件中读取。问题是buff充满了正义感。
CCD_ 7仅填充缓冲器直到CCD_。如果你试图使用一个字符串,那么在ReadFile
返回后,你必须自己用null终止它
buff [dwBytesRead] = 0;
您不应该使用128作为nNumberOfBytesToRead
,因为您在打印字符串时可能会越界(或者将buff
视为以0结尾的字符串)。还要检查dwBytesRead
是否真的读取了那么多字节,并按照@James McLaughlin的建议0终止字符串。
相关文章:
- 修复"-Wunused-parameter"取决于预处理器条件的警告
- C++模板错误:"invalid explicitly-specified argument for template parameter"
- 为什么"types may not be defined in parameter types"
- 如何理解"abstract-declarator containing an ellipsis shall only be used in a parameter-declaration"
- 为什么这段代码抱怨"a non-type template parameter cannot have type"?
- 如何抛出"template parameter"类型的异常?
- 如何在开关语句中使用 cin "as a parameter"
- 派生类中函数参数变化的虚函数按常量类型在"function parameter"会破坏虚拟机制吗?
- 在 lambda(parameter) 中为 std::transform with std::sregex_token
- 如何修复此"argument of type incompatible with parameter"错误?
- 谷歌模拟 - 怎么说"function must be called ONCE with a certain parameter but ok to be called many times with
- CUDA 内核"Only a single pack parameter is allowed"解决方法?
- "Cannot convert parameter 1 from double to float"虽然没有更改参数
- 读取文件函数lpbuffer和字节以读取澄清
- rvalue for a std::string parameter
- 在 MSVC 上,为什么没有出现 std::string 的警告"unreferenced formal parameter"?
- result_of, make_tuple, parameter pack
- "useinbandfec is a unidirectional receive-only parameter"作品中是什么意思?
- 重新定义类<template-parameter-1-2>的默认参数
- ReadFile lpBuffer parameter