Exception while opening file

谁都会走 提交于 2019-12-08 03:56:32

问题


I have a VC++ application and in my application i have some basic file operations.

Below is the defaulting code

CStdioFile cFile;
CFileException e;
CString sReport;
CString sHtmlfile = "testreport.html"
OutputDebugString((sHtmlfile));
if (!cFile.Open(sHtmlfile,CFile::modeCreate | CFile::modeWrite, &e ))
{
}

The problem is my application executes this piece of code every few minutes. and it works fine.

After several runs of the code the cFile.Open() function fails. I tried to get the error message

TCHAR szError[1024];
e.GetErrorMessage(szError,1024);
OutputDebugString((szError));

The irony is the szError error message is "No error occured".

This again works once i restart my application. Any idea why this occurs.

Thanks in advance.


回答1:


Do you have multiple instances running? I suggest you use Process Explorer when the error occurs to see if any other handles to the said file exist.

And GetLastError will report the error reported by the last API function. If there were any other API calls between the failing API call and the call to GetLastError, then the last error value is overwritten. (As @sbi has already pointed out in the comments.)




回答2:


Maube you forget to close your file and it come out of file descriptors. They are all closed when you quit your application, then you can run it again. Check if your files are closed or not.

OK. If this is not the above case, what could it be ? You get the error message from cFile.Open, hence we can believe it's accurate.

I'm not sure what would happen if another file of the same name is already open by the current process, or if you try to open a file with a strange name, like empty string. To sort these out you can also print the name of the file you are opening with the error (and also trace the cases where no error occurs).




回答3:


You are using C++. Your error could be completely somewhere else. I've had a pointer bug that resulted in clean code coughing up an error.

Have you tried building in release mode?

I would suggest trying to step through and perhaps narrow down where your error appears.



来源:https://stackoverflow.com/questions/2506485/exception-while-opening-file

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