How do I check to see if a text file is empty or d

2019-01-20 20:15发布

问题:

I wrote a method which takes in a file name, checks if the file exists and has content, then proceeds to read 6 numbers in the file into 6 int variables and return true. If the file doesn't exist, or doesn't have content, it returns false.

However, when I call the method and give it a file that exists, it returns false. I'm not sure where I went wrong.

Here's my code:

bool readHSV(string the_file)
{
    if(ifstream(the_file)){
        fstream myfile(the_file, ios_base::in);
        myfile >> 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;
}

The contents of the .txt file I am using:

4
22
68
192
162
247

回答1:

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.

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;
}


回答2:

You can use <filesystem> like this:

#include <filesystem>

namespace fs = std::filesystem; // for brevity

// ...

bool func(std::string const& filename)
{
    if(!fs::exists(filename) || fs::file_size(filename) == 0)
        return false;

    std::ifstream ifs(filename);

    if(!ifs)
        return false;

    // do stuff here with ifs

    return true;
}