开发者

Reading a stream in C++

I have the following code:

    ifstream initFile;
    init开发者_JAVA技巧File.open("D:\\InitTLM.csv");
    if(initFile.is_open())
    {

      // Process file

    }

The file is not opening. The file does exist on the D: drive. Is there a way to find out exactly why this file cannot be found? Like an "errno"?


You should be able to use your OS's underlying error reporting mechanism to get the reason (because the standard library is built on the OS primitives). The code won't be portable, but it should get you to the bottom of your issue.

Since you appear to be using Windows, you would use GetLastError to get the raw code and FormatMessage to convert it to a textual description.


Answered here I believe: Get std::fstream failure error messages and/or exceptions


The STL is not great at reporting errors. Here's the best you can do within the standard:

  ifstream initFile;
  initFile.exceptions(ifstream::eofbit|ifstream::failbit|ifstream::badbit);
  try
    { 
      initFile.open("D:\\InitTLM.csv");
      // Process File
    }
  catch(ifstream::failure e) 
    {
      cout << "Exception opening file:" << e.what() << endl;
    }

In my experience, the message returned by what() is usually useless.


Check the permissions on the root of the D: drive. You may find that your compiled executable, or the service under which your debugger is running, does not have sufficient access privileges to open that file.

Try changing the permissions on the D:\ root directory temporarily to "Everyone --> Full Control", and see if that fixes the issue.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜