如何检查文本文件是否为空或c ++中不存在? [英] How do I check to see if a text file is empty or does not exist in c++?

查看:148
本文介绍了如何检查文本文件是否为空或c ++中不存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个方法,该方法接受文件名,检查文件是否存在并具有内容,然后继续将文件中的6个数字读入6个int变量并返回true.如果文件不存在或不包含内容,则返回false.

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.

但是,当我调用该方法并为其提供一个存在的文件时,它返回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.

这是我的代码:

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

我正在使用的.txt文件的内容:

The contents of the .txt file I am using:

4
22
68
192
162
247

推荐答案

函数返回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;
}

这篇关于如何检查文本文件是否为空或c ++中不存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆