`

linux遍历目录下所有文件

阅读更多

#include <sys/types.h>
#include <dirent.h>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
using namespace std;

#ifndef NULL
#define NULL 0
#endif

void err_sys(char* pszVal, ...)
{
        if (NULL == pszVal)
        {
                return;
        }

        int nLen = strlen(pszVal);

        if (nLen <= 0)
        {
                return;
        }

        //malloc buffer
        char* pszBuf = new char[1024 + nLen * 2];

        if (NULL == pszBuf)
        {
                return;
        }

        do
        {
                try
                {
                        va_list vl;
                        va_start(vl, pszVal);
                        vsprintf(pszBuf, pszVal, vl);
                        va_end(vl);

                        //print
                        cout << pszBuf << endl;
                }
                catch (...)
                {
                        break;
                }
        } while (0);

        if (NULL != pszBuf)
        {
                delete pszBuf;
                pszBuf = NULL;
        }
}

void err_quit(char* pszVal, ...)
{
        //err_sys(pszVal, __VA_ARGS__);

        cout << pszVal << endl;
        exit(0);
} 

int main(int argc, char** argv)
{
        DIR* pDir = NULL;
        struct dirent* pstDir = NULL;

        if (2 != argc)
        {
                err_quit("a single argument (the directory name) is required");
        }

        if (NULL == (pDir = opendir(argv[1])) )
        {
                err_sys("can't open %s", argv[1]);
        }

        while ( NULL != (pstDir = readdir(pDir)) )
        {
                cout << pstDir->d_name <<endl;
        }

        closedir(pDir);

        return 0;
}
 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics