用C++ 怎样判断文件夹是否为空

如题所述

c++判断文本文件为空,必须要先读一下文件(读一个字符),才能判断是否为空。
刚打开文件时,文件状态标识都是初始化状态,eof()函数是根据文件状态标识来判断当前是否到了文件尾,而不是用来判断文件是否为空。当读取文件数据时,遇到文件尾时,系统会更改文件状态标识为文件尾,同时,返回EOF标志。
参考代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

#include <fstream>
#include <iostream>
using namespace std;
int main()
{
fstream file;
int ch;
file.open("a.txt",ios::in);
ch=file.get(); //试图去读一个字符
if(file.eof()) //或 if ( ch==EOF ) //一个字符都未读到,表示文件为空
{
cout<<"文件为空"<<endl;
}
file.close();
温馨提示:答案为网友推荐,仅供参考
第1个回答  2016-12-22
#include <iostream>
#include <windows.h>
using namespace std;
 
int main(void)
{
    HANDLE hFind;
    WIN32_FIND_DATA FindFileData;
    if((hFind=FindFirstFileA("E:\\music\\*.*",&FindFileData)) != INVALID_HANDLE_VALUE)//注意替换路径
    {
        BOOL bFind = TRUE;   
        BOOL EmptyDirectory = TRUE;
        while(bFind)
        {
            if(strcmp(FindFileData.cFileName,".") == 0
                || strcmp(FindFileData.cFileName,"..") == 0)
            {
                bFind = FindNextFile(hFind,&FindFileData);
            }
            else
            {
                //有子文件夹也算非空
                EmptyDirectory = FALSE;
                break;
            }
        }
        if(EmptyDirectory)
        {
            cout<<"Empty"<<endl;
        }
        else
        {
            cout<<"Not Empty"<<endl;
        }
    }
    else
    {
        cout<<"Path does not exist."<<endl;
    }
    return 0;
}

资料来源

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网