在循环中写入多行 [英] Writing Multiple Lines within Loop

查看:30
本文介绍了在循环中写入多行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经声明

char body[1000] ;
HANDLE myFile;

我已经在上一节创建了一个文件并编写了标题.写得很好.

I already have a previous section where I create a file and write the title. It writes well.

它有以下没有循环的命令.

It has following commands without loop.

HANDLE myFile=CreateFile("filename.txt",GENERIC_ALL,FILE_SHARE_WRITE,0,CREATE_NEW,FILE_ATTRIBUTE_NORMAL,0);
char* HeadingStr="a1 a2 a3 a4 a5 a6 a7 a8 \n";
WriteFile(myFile,HeadingStr,lstrlen(HeadingStr),0,NULL);
CloseHandle(myFile);

然后我有以下代码

loop{ (100 times)

myFile=CreateFile("filename.txt",FILE_APPEND_DATA,FILE_SHARE_WRITE,0,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,0);
BufferNo=sprintf(body,"%f %f %f %f %f %f %f %f \n",a1,a2,a3,a4,a5,a6,a7,a8);
WriteFile(myFile,body,BufferNo,0,NULL);
CloseHandle(myFile);

}

循环实际上是我从设备接收到的消息.所以,这不必对此做任何事情.

The loop is actually a message I am receiving from a device. So, that does not have to do anything to this.

运行代码后,错误Access Violation Error并指向

After running the code, The error Access Violation Error and pointing to

WriteFile(myFile,body,BufferNo,0,NULL);

如果我检查文件,我得到

If I check the file, I get

a1 a2 a3 a4 a5 a6 a7 a8 (rectangle: may be way of text editor saying line break) and then 2 4 23 21 12 431 23 32 (same rectangle)

仅此而已.错误指出这不是由于来自设备的消息.如果您需要更多详细信息,请告诉我.错误在哪里?

This is all. The error notes that this is not due to message coming from device. If you need further details, let me know. Where in here lies the error?

附言在此之前我问了一个问题.在此错误发生之前包含错误,并且还包含该问题的解决方案.我在那里问过,但由于不活动,我再问一次.但问题是不同的.

P.S. I asked a question prior to this. that contained error before this error occured and also contained solution tothat problem. I asked there but due to inactivity, I am asking again. Problems are different though.

推荐答案

WriteFile 原型:

WriteFile prototype:

BOOL WINAPI WriteFile(
  _In_         HANDLE hFile,
  _In_         LPCVOID lpBuffer,
  _In_         DWORD nNumberOfBytesToWrite,
  _Out_opt_    LPDWORD lpNumberOfBytesWritten,
  _Inout_opt_  LPOVERLAPPED lpOverlapped
);

lpNumberOfBytesWrittenlpOverlapped 不能都是 NULL.由于您为 lpNumberOfBytesWritten 传递 0lpOverlappedNULL,它试图写入地址位置 0,导致异常.

lpNumberOfBytesWritten and lpOverlapped cannot both be NULL. Since you're passing 0 for lpNumberOfBytesWritten whilst lpOverlapped is NULL, it's trying to write to address location 0, which causes the exception.

给它一个虚拟变量.

...
DWORD dummy = 0;
WriteFile(myFile,body,BufferNo,&dummy,NULL);
...

您还应该将 CreateFile(...)CloseHandle(...) 移动到循环块之外(无需重复打开和关闭文件).

You should also move the CreateFile(...) and CloseHandle(...) outside of the loop block (no need to repeatedly open and close the file).

这篇关于在循环中写入多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆