且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检查文本文件是否为空或c ++中不存在?

更新时间:2023-11-26 22:06:28

函数返回false的唯一方法是ifstream(the_file)失败,这意味着它根本无法打开文件,无论它是否存在.如果该文件确实存在,但ifstream仍然失败,请再次检查the_file包含正确的路径和文件名,并且您的应用有权访问该文件.

The only way your function can return false is if ifstream(the_file) fails, meaning it can't open the file at all, whether it exists or not. If the file does exist but ifstream still fails, double check that the_file contains the correct path and filename, and that your app has rights to access the file.

请注意,您将打开文件两次,一次是通过ifstream,另一次是通过fstream.您不需要这样做.您应该只打开文件一次,如果能够从文件中读取所需的值,则返回true,例如:

Note that you are opening the file twice, once by ifstream and again by fstream. You don't need to do that. You should open the file only once, and return true if you are able to read the values you want from it, eg:

bool readHSV(const string &the_file)
{
    ifstream inFile(the_file);
    if (inFile >> h_min >> h_max >> s_min >> s_max >> v_min >> v_max)
    {
        cout << h_min << endl
             << h_max << endl
             << s_min << endl
             << s_max << endl
             << v_min << endl
             << v_max;
        getchar();
        return true;
    }
    return false;
}