C++ ifstream is_open() fails [duplicate]

断了今生、忘了曾经 提交于 2019-12-12 01:58:17

问题


Why does my is_open() always fail and goes into the else statement which displays the error message?

Another method of mine is similar to this yet it worked.

#include <iostream>
#include <fstream>
using namespace std;

int main() {
     string userName;

    cout << "Please login to your account here!" << endl;
    cout << "Username: ";
    cin >> userName;

    ifstream openSalt;
    openSalt.open("salt.txt"); //open the file

    if(openSalt.is_open()) //if file is open
    {
        string temp;

        while (getline(openSalt,temp))
        {
            //gets content
            //if user exists, login
            //else, exit
        }
        openSalt.close();
    }
    else
    {
        cout << "Error opening file!" << endl;
        exit(1);
    }
    return 0;
}

回答1:


Assuming code is main function etc, the code works for me.

The issue is more likely to be that what ether tool/IDE you are using to compile the program sets the current folder to a different place to what you are expecting, and then is not the place the salt.txt file is in.




回答2:


Check two things.

  1. If the file really exists in the current folder from where you program is run ?
  2. Do you have correct permissions to open the file ?



回答3:


use this function to get the error :

std::string GetLastErrorAsString()
{
    //Get the error message, if any.
    DWORD errorMessageID = ::GetLastError();
    if (errorMessageID == 0)
        return std::string(); //No error message has been recorded

    LPSTR messageBuffer = nullptr;
    size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
        NULL, errorMessageID, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&messageBuffer, 0, NULL);

    std::string message(messageBuffer, size);

    //Free the buffer.
    LocalFree(messageBuffer);

    return message;
}

then call it in your else

else
{
    cout << GetLastErrorAsString() << endl;
    system("pause");
    exit(1);
}

I used your code and it worked, make sure the file is in the same directory, make sure you are not working with a salt.txt.txt file (common mistake)



来源:https://stackoverflow.com/questions/38587248/c-ifstream-is-open-fails

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