写文件函数 C++
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9174947/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
WriteFile function C++
提问by discodowney
Im trying to use the WriteFile function. Ive been working off this example
我正在尝试使用 WriteFile 函数。我一直在研究这个例子
http://msdn.microsoft.com/en-us/library/ms900134.aspx
http://msdn.microsoft.com/en-us/library/ms900134.aspx
Here the buffer that is passed to WriteFile is filled from ReadFile. But I dont want to do it that way. I just want to write a string like "Example text testing WriteFile" or something. But im not sure what values the parameters should have. Ive tried looking around on google but couldnt find anything. Anyone know how i do this?
这里传递给 WriteFile 的缓冲区是从 ReadFile 填充的。但我不想那样做。我只想写一个像“Example text testing WriteFile”之类的字符串。但我不确定参数应该有什么值。我试过在谷歌上环顾四周,但找不到任何东西。有谁知道我是怎么做到的?
回答by Some programmer dude
From MSDN:
从MSDN:
BOOL WINAPI WriteFile(
__in HANDLE hFile,
__in LPCVOID lpBuffer,
__in DWORD nNumberOfBytesToWrite,
__out_opt LPDWORD lpNumberOfBytesWritten,
__inout_opt LPOVERLAPPED lpOverlapped
);
- The first argument is the handle to the file.
- The second argument is a pointer to the data you want to write. In your case it's the string.
- The third argument is the length of the data you want to write. In your case it will be something like
strlen(str)
. - The fourth argument is a pointer to a
DWORD
variable that will receive the number of bytes actually written. - The fifth and last parameter can be NULL for now.
- 第一个参数是文件的句柄。
- 第二个参数是指向要写入的数据的指针。在你的情况下,它是字符串。
- 第三个参数是要写入的数据的长度。在您的情况下,它将类似于
strlen(str)
. - 第四个参数是一个指向
DWORD
变量的指针,该变量将接收实际写入的字节数。 - 第五个也是最后一个参数现在可以为 NULL。
You use it like this:
你像这样使用它:
char str[] = "Example text testing WriteFile";
DWORD bytesWritten;
WriteFile(fileHandle, str, strlen(str), &bytesWritten, NULL);
If WriteFile
returns FALSE
then there was an error. Use the GetLastError
function to find out the error code.
如果WriteFile
返回FALSE
则有错误。使用该GetLastError
函数找出错误代码。
回答by Nick Shaw
A simple example of writing a string:
编写字符串的简单示例:
(hOutFile
here is an open file handle from a call to CreateFile
):
(hOutFile
这是来自调用的打开文件句柄CreateFile
):
{
DWORD dwBytesWritten = 0;
char Str[] = "Example text testing WriteFile";
WriteFile( hOutFile, Str, strlen(Str), &dwBytesWritten, NULL );
}
EDIT: Check the MSDNfunction definition for what each parameter does.
编辑:检查MSDN函数定义以了解每个参数的作用。