前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >如何使用 C 或 C++ 获取目录中的文件列表

如何使用 C 或 C++ 获取目录中的文件列表

作者头像
ClearSeve
发布2022-02-10 20:51:34
7.6K0
发布2022-02-10 20:51:34
举报
文章被收录于专栏:ClearSeveClearSeve

问题

如何使用 C 或 C++ 获取目录中的文件列表?我的程序不允许使用 ls 这样的命令。

回答

Linux 平台

可以使用 opendir,如下,

代码语言:javascript
复制
char dirname[] = "/usr/local"
DIR *dir_ptr;
struct dirent *direntp;

dir_ptr = opendir(dirname);
if (dir_ptr == NULL)
    fprintf(stderr,"Ls: can not open %s",dirname);
else
{
    direntp = readdir(dir_ptr);
    while(direntp == NULL)
        printf("%s\n",direntp->d_name);

    closedir(dir_ptr);
}

Windows 平台

代码语言:javascript
复制
#include <windows.h>
#include <tchar.h>
#include <stdio.h>

void _tmain(int argc, TCHAR *argv[])
{
    WIN32_FIND_DATA FindFileData;
    HANDLE hFind;

    if (argc != 2)
    {
       _tprintf(TEXT("Usage: %s [target_file]\n"), argv[0]);
       return;
    }

    _tprintf (TEXT("Target file is %s\n"), argv[1]);
    hFind = FindFirstFile(argv[1], &FindFileData);
    if (hFind == INVALID_HANDLE_VALUE) 
    {
       printf ("FindFirstFile failed (%d)\n", GetLastError());
       return;
    } 
    else 
    {
       _tprintf (TEXT("The first file found is %s\n"), FindFileData.cFileName);
       FindClose(hFind);
    }
}

跨平台下 C++17

代码语言:javascript
复制
#include <string>
#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;

int main()
{
    std::string path = "/path/to/directory";
    for (const auto & entry : fs::directory_iterator(path))
        std::cout << entry.path() << std::endl;
}
本文参与?腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2022年1月24日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客?前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与?腾讯云自媒体分享计划? ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 问题
  • 回答
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
http://www.vxiaotou.com