c++判断文件是否为空
时间: 2023-08-06 13:02:51 浏览: 83
可以使用C++中的文件流来判断文件是否为空。具体操作如下:
```c++
#include <fstream>
using namespace std;
int main()
{
ifstream file("filename.txt"); //打开文件
if (file.peek() == ifstream::traits_type::eof()) //判断文件是否为空
{
//文件为空
}
else
{
//文件不为空
}
file.close(); //关闭文件
return 0;
}
```
在上述代码中,我们使用`ifstream`类来打开文件,并使用`peek()`函数来读取文件的第一个字符。如果文件为空,则`peek()`函数返回`EOF`(-1),否则返回文件的第一个字符。因此,我们可以通过判断`peek()`函数的返回值是否等于`EOF`来判断文件是否为空。
相关问题
C++,判断一个文件是否为空
在 C++ 中,你可以使用 `std::ifstream` 来打开文件并判断文件是否为空。以下是一个示例代码:
```cpp
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ifstream file("filename");
if (file.peek() == std::ifstream::traits_type::eof()) {
cout << "File is empty" << endl;
} else {
cout << "File is not empty" << endl;
}
file.close();
return 0;
}
```
其中,`std::ifstream::traits_type::eof()` 可以判断文件是否已经到达文件末尾(即文件是否为空)。如果文件为空,则 `file.peek()` 返回值为 `std::ifstream::traits_type::eof()`。
c++的fstream是否为空判断
可以通过调用 `fail()` 或 `good()` 函数来判断 `fstream` 是否为空。若 `fail()` 函数返回 `true`,则说明出现了错误,`fstream` 为空;若 `good()` 函数返回 `false`,则说明读取文件失败,`fstream` 为空。示例代码如下:
```c++
#include <fstream>
#include <iostream>
int main() {
std::ifstream ifs("example.txt");
if (!ifs.is_open()) {
std::cerr << "Failed to open file!" << std::endl;
return -1;
}
if (ifs.fail()) {
std::cerr << "Failed to read file!" << std::endl;
} else {
std::cout << "File opened successfully." << std::endl;
}
ifs.close();
return 0;
}
```