Checking for an empty file in C++

前端 未结 8 1966
抹茶落季
抹茶落季 2020-11-27 03:35

Is there an easy way to check if a file is empty. Like if you are passing a file to a function and you realize it\'s empty, then you close it right away? Thanks.

E

相关标签:
8条回答
  • 2020-11-27 04:08

    Perhaps something akin to:

    bool is_empty(std::ifstream& pFile)
    {
        return pFile.peek() == std::ifstream::traits_type::eof();
    }
    

    Short and sweet.


    With concerns to your error, the other answers use C-style file access, where you get a FILE* with specific functions.

    Contrarily, you and I are working with C++ streams, and as such cannot use those functions. The above code works in a simple manner: peek() will peek at the stream and return, without removing, the next character. If it reaches the end of file, it returns eof(). Ergo, we just peek() at the stream and see if it's eof(), since an empty file has nothing to peek at.

    Note, this also returns true if the file never opened in the first place, which should work in your case. If you don't want that:

    std::ifstream file("filename");
    
    if (!file)
    {
        // file is not open
    }
    
    if (is_empty(file))
    {
        // file is empty
    }
    
    // file is open and not empty
    
    0 讨论(0)
  • 2020-11-27 04:11

    use this: data.peek() != '\0'

    I've been searching for an hour until finaly this helped!

    0 讨论(0)
提交回复
热议问题