在C ++中检查一个空文件 [英] Checking for an empty file in C++
问题描述
有一个简单的方法来检查文件是否为空。就像你把一个文件传递给一个函数,你意识到它是空的,那么你马上关闭它?谢谢。
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.
编辑,我尝试使用fseek方法,但我收到一个错误,说'不能将ifstream转换为FILE *'。
Edit, I tried using the fseek method, but I get an error saying 'cannot convert ifstream to FILE *'.
我的函数的参数是
myFunction(ifstream &inFile)
推荐答案
可能类似于:
bool is_empty(std::ifstream& pFile)
{
return pFile.peek() == std::ifstream::traits_type::eof();
}
很甜美。
由于您的错误,其他答案使用C风格文件访问,您会得到 FILE *
具体函数。
With concerns to your error, the other answers use C-style file access, where you get a FILE*
with specific functions.
相反,你和我正在使用C ++流,因此不能使用这些函数。上面的代码工作在一个简单的方式: peek()
将窥视流,并返回,而不删除,下一个字符。如果到达文件的结尾,它返回 eof()
。 Ergo,我们只是 peek()
在流,看看是否 eof()
,因为一个空文件没有以查看。
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.
注意,如果文件从未打开过,这也会返回true,这在您的情况下应该工作。如果你不想这样:
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
这篇关于在C ++中检查一个空文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!