Exception while opening file

2019-06-01 09:21发布

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.

3条回答
Explosion°爆炸
2楼-- · 2019-06-01 09:51

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.)

查看更多
萌系小妹纸
3楼-- · 2019-06-01 10:00

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.

查看更多
狗以群分
4楼-- · 2019-06-01 10:08

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).

查看更多
登录 后发表回答