Error Writing to File in Visual Studio

余生长醉 提交于 2019-12-25 07:09:08

问题


Unhandled exception at 0x102e1cee (msvcr100d.dll) in filename.exe 0xC0000005: Access violation writing location 0x00416858 on.

The debugging points to line:

if (_putc_nolock(ch, f) == EOF)

of code

#else  /* _UNICODE */
    if (_putc_nolock(ch, f) == EOF)
#endif  /* _UNICODE */
        *pnumwritten = -1;
    else
        ++(*pnumwritten);
}

in output.c which I believe is linked in visual studio library. I did not link it.

My code is:

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

I initially wrote to file with following lines. I had to write the heading.

HANDLE myFile=CreateFile("Sample.txt",GENERIC_WRITE,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);

How do I solve this error? Note I have write permission. I ran as administrator, too. Note that I have already defined BufferNo, myFile, outside the use in last code.

UPDATE I removed body="" Now I get

filename.exe triggered a breakpoint.

pointing to the file mentioned in comment below.

**EDIT**

Now, I have problem writing. Error reads

Unhandled exception at 0x7c811384 in stabilo.exe: 0xC0000005: Access violation writing location 0x00000000 on.

and points to line

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

回答1:


The variable body in this section is incorrect.

body="";
...
BufferNo=sprintf(body,"%.5f %[3].5f %[3].5f %[3].5f %[3].5f %[3].5f %[3].5f %[3].5f\n",
                      a1,a2,a3,a4,a5,a6,a7,a8);

Presumably it's a char * (alhtough I'm just guessing), which means you are trying to write a bunch of number values to a constant string capable of holding exactly zero characters. Since it's a constant, it's non-writeable.

Change it to char body[1000]; or something similar.




回答2:


Your sprintf overruns the buffer for sure. Even worse: you try to write over a string literal.



来源:https://stackoverflow.com/questions/17404683/error-writing-to-file-in-visual-studio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!