Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/149.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何在C++;?_C++_File_Directory - Fatal编程技术网

C++ 如何在C++;?

C++ 如何在C++;?,c++,file,directory,C++,File,Directory,如何获得目录中的文件列表以便处理每个文件?但是boost::filesystem可以做到这一点:解决这一问题需要一个特定于平台的解决方案。查找unix/linux上的opendir()或Windows上的FindFirstFile()。或者,有许多库将为您处理特定于平台的部分。下面是Linux上C语言的一个示例。如果您使用的是Linux,并且不介意在ANSIC中执行这一点 #include <dirent.h> DIR *dpdf; struct dirent *epdf; dp

如何获得目录中的文件列表以便处理每个文件?

但是
boost::filesystem
可以做到这一点:

解决这一问题需要一个特定于平台的解决方案。查找unix/linux上的opendir()或Windows上的FindFirstFile()。或者,有许多库将为您处理特定于平台的部分。

下面是Linux上C语言的一个示例。如果您使用的是Linux,并且不介意在ANSIC中执行这一点

#include <dirent.h>

DIR *dpdf;
struct dirent *epdf;

dpdf = opendir("./");
if (dpdf != NULL){
   while (epdf = readdir(dpdf)){
      printf("Filename: %s",epdf->d_name);
      // std::cout << epdf->d_name << std::endl;
   }
}
closedir(dpdf);
#包括
DIR*dpdf;
结构方向*epdf;
dpdf=opendir(“./”);
if(dpdf!=NULL){
while(epdf=readdir(dpdf)){
printf(“文件名:%s”,epdf->d_名称);

//std::cout d_name如果您在Windows中使用MSVC,那么MSDN库

下面是该链接的代码:

#include <windows.h>
#include <tchar.h> 
#include <stdio.h>
#include <strsafe.h>

void ErrorHandler(LPTSTR lpszFunction);

int _tmain(int argc, TCHAR *argv[])
{
   WIN32_FIND_DATA ffd;
   LARGE_INTEGER filesize;
   TCHAR szDir[MAX_PATH];
   size_t length_of_arg;
   HANDLE hFind = INVALID_HANDLE_VALUE;
   DWORD dwError=0;

   // If the directory is not specified as a command-line argument,
   // print usage.

   if(argc != 2)
   {
      _tprintf(TEXT("\nUsage: %s <directory name>\n"), argv[0]);
      return (-1);
   }

   // Check that the input path plus 2 is not longer than MAX_PATH.

   StringCchLength(argv[1], MAX_PATH, &length_of_arg);

   if (length_of_arg > (MAX_PATH - 2))
   {
      _tprintf(TEXT("\nDirectory path is too long.\n"));
      return (-1);
   }

   _tprintf(TEXT("\nTarget directory is %s\n\n"), argv[1]);

   // Prepare string for use with FindFile functions.  First, copy the
   // string to a buffer, then append '\*' to the directory name.

   StringCchCopy(szDir, MAX_PATH, argv[1]);
   StringCchCat(szDir, MAX_PATH, TEXT("\\*"));

   // Find the first file in the directory.

   hFind = FindFirstFile(szDir, &ffd);

   if (INVALID_HANDLE_VALUE == hFind) 
   {
      ErrorHandler(TEXT("FindFirstFile"));
      return dwError;
   } 

   // List all the files in the directory with some info about them.

   do
   {
      if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
      {
         _tprintf(TEXT("  %s   <DIR>\n"), ffd.cFileName);
      }
      else
      {
         filesize.LowPart = ffd.nFileSizeLow;
         filesize.HighPart = ffd.nFileSizeHigh;
         _tprintf(TEXT("  %s   %ld bytes\n"), ffd.cFileName, filesize.QuadPart);
      }
   }
   while (FindNextFile(hFind, &ffd) != 0);

   dwError = GetLastError();
   if (dwError != ERROR_NO_MORE_FILES) 
   {
      ErrorHandler(TEXT("FindFirstFile"));
   }

   FindClose(hFind);
   return dwError;
}


void ErrorHandler(LPTSTR lpszFunction) 
{ 
    // Retrieve the system error message for the last-error code

    LPVOID lpMsgBuf;
    LPVOID lpDisplayBuf;
    DWORD dw = GetLastError(); 

    FormatMessage(
        FORMAT_MESSAGE_ALLOCATE_BUFFER | 
        FORMAT_MESSAGE_FROM_SYSTEM |
        FORMAT_MESSAGE_IGNORE_INSERTS,
        NULL,
        dw,
        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
        (LPTSTR) &lpMsgBuf,
        0, NULL );

    // Display the error message and exit the process

    lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT, 
        (lstrlen((LPCTSTR)lpMsgBuf)+lstrlen((LPCTSTR)lpszFunction)+40)*sizeof(TCHAR)); 
    StringCchPrintf((LPTSTR)lpDisplayBuf, 
        LocalSize(lpDisplayBuf) / sizeof(TCHAR),
        TEXT("%s failed with error %d: %s"), 
        lpszFunction, dw, lpMsgBuf); 
    MessageBox(NULL, (LPCTSTR)lpDisplayBuf, TEXT("Error"), MB_OK); 

    LocalFree(lpMsgBuf);
    LocalFree(lpDisplayBuf);
}
#包括
#包括
#包括
#包括
void ErrorHandler(LPTSTR lpsz函数);
int_tmain(int argc,TCHAR*argv[])
{
WIN32_查找_数据ffd;
大整数文件大小;
TCHAR szDir[MAX_PATH];
参数的大小和长度;
句柄hFind=无效的句柄值;
DWORD dwError=0;
//如果未将目录指定为命令行参数,
//打印使用。
如果(argc!=2)
{
_tprintf(文本(“\n用法:%s\n”),argv[0]);
返回(-1);
}
//检查输入路径加2是否比最大路径长。
字符串长度(argv[1]、最大路径和长度);
if(参数的长度>(最大路径-2))
{
_tprintf(文本(“\n目录路径太长。\n”);
返回(-1);
}
_tprintf(文本(“\n目标目录为%s\n\n”),argv[1]);
//准备用于FindFile函数的字符串。首先,复制
//字符串添加到缓冲区,然后将“\*”追加到目录名。
StringCchCopy(szDir,MAX_PATH,argv[1]);
StringCchCat(szDir,最大路径,文本(“\\*”);
//查找目录中的第一个文件。
hFind=FindFirstFile(szDir和ffd);
if(无效的句柄值==hFind)
{
ErrorHandler(文本(“FindFirstFile”);
返回dwError;
} 
//列出目录中的所有文件及其相关信息。
做
{
if(ffd.dwFileAttributes和文件属性目录)
{
_tprintf(文本(“%s\n”),ffd.cFileName);
}
其他的
{
filesize.LowPart=ffd.nFileSizeLow;
filesize.HighPart=ffd.nFileSizeHigh;
_tprintf(文本(“%s%ld字节\n”)、ffd.cFileName、filesize.QuadPart);
}
}
while(FindNextFile(hFind,&ffd)!=0);
dwError=GetLastError();
if(dwError!=错误\u无\u更多\u文件)
{
ErrorHandler(文本(“FindFirstFile”);
}
FindClose(hFind);
返回dwError;
}
无效错误处理程序(LPTSTR LPSZ函数)
{ 
//检索最后一个错误代码的系统错误消息
LPVOID lpMsgBuf;
LPVOID lpDisplayBuf;
DWORD dw=GetLastError();
格式化消息(
格式化消息分配缓冲区
格式化来自\u系统的\u消息\u|
格式化\u消息\u忽略\u插入,
无效的
dw,
MAKELANGID(LANG_中立,SUBLANG_默认),
(LPTSTR)和lpMsgBuf,
0,空);
//显示错误消息并退出进程
lpDisplayBuf=(LPVOID)LocalAlloc(LMEM_zeronit,
(lstrlen((LPCTSTR)lpMsgBuf)+lstrlen((LPCTSTR)lpszFunction)+40)*sizeof(TCHAR));
StringCchPrintf((LPTSTR)lpDisplayBuf,
LocalSize(lpDisplayBuf)/sizeof(TCHAR),
文本(“%s失败,错误为%d:%s”),
lpsz函数、dw、lpMsgBuf);
消息框(空,(LPCTSTR)lpDisplayBuf,文本(“错误”),MB_OK);
本地免费(lpMsgBuf);
LocalFree(lpDisplayBuf);
}

您必须使用操作系统调用(例如Win32 API)或其周围的包装器。我倾向于使用它,因为它是优于Win32 API的接口(以及跨平台)

如果您希望使用Win32 API,Microsoft在msdn上有一个列表和。以下是我使用的内容:

/* Returns a list of files in a directory (except the ones that begin with a dot) */

void GetFilesInDirectory(std::vector<string> &out, const string &directory)
{
#ifdef WINDOWS
    HANDLE dir;
    WIN32_FIND_DATA file_data;

    if ((dir = FindFirstFile((directory + "/*").c_str(), &file_data)) == INVALID_HANDLE_VALUE)
        return; /* No files found */

    do {
        const string file_name = file_data.cFileName;
        const string full_file_name = directory + "/" + file_name;
        const bool is_directory = (file_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;

        if (file_name[0] == '.')
            continue;

        if (is_directory)
            continue;

        out.push_back(full_file_name);
    } while (FindNextFile(dir, &file_data));

    FindClose(dir);
#else
    DIR *dir;
    class dirent *ent;
    class stat st;

    dir = opendir(directory);
    while ((ent = readdir(dir)) != NULL) {
        const string file_name = ent->d_name;
        const string full_file_name = directory + "/" + file_name;

        if (file_name[0] == '.')
            continue;

        if (stat(full_file_name.c_str(), &st) == -1)
            continue;

        const bool is_directory = (st.st_mode & S_IFDIR) != 0;

        if (is_directory)
            continue;

        out.push_back(full_file_name);
    }
    closedir(dir);
#endif
} // GetFilesInDirectory
/*返回目录中的文件列表(以点开头的文件除外)*/
void GetFilesInDirectory(std::vector&out,const string&directory)
{
#ifdef窗口
handledir;
WIN32_查找_数据文件_数据;
if((dir=FindFirstFile((directory+“/*”).c_str(),&file_data))==INVALID_HANDLE_值)
return;/*未找到任何文件*/
做{
const string file_name=file_data.cFileName;
常量字符串完整文件名=目录+“/”+文件名;
const bool is_directory=(file_data.dwFileAttributes&file_attributes_directory)!=0;
如果(文件名[0]='。)
继续;
if(is_目录)
继续;
out.push_back(完整文件名);
}while(FindNextFile(dir和file_data));
FindClose(dir);
#否则
DIR*DIR;
类指令;
类别统计st;
dir=opendir(目录);
while((ent=readdir(dir))!=NULL){
常量字符串文件\u name=ent->d\u name;
常量字符串完整文件名=目录+“/”+文件名;
如果(文件名[0]='。)
继续;
if(stat(full_file_name.c_str(),&st)=-1)
继续;
const bool is_directory=(st.st_mode&S_IFDIR)!=0;
if(is_目录)
继续;
out.push_back(完整文件名);
}
closedir(dir);
#恩迪夫
}//GetFilesInDirectory

将属性设置为仅查找目录。

或者执行此操作,然后读取test.txt:

#include <windows.h>

int main() {    
system("dir /b > test.txt");
}
#包括
int main(){
系统(“dir/b>test.txt”);
}
“/b”表示只返回文件名,不返回其他信息。

void getFilesList(字符串文件路径、字符串扩展名、向量和返回文件名)
void getFilesList(String filePath,String extension, vector<string> & returnFileName)
{
    WIN32_FIND_DATA fileInfo;
    HANDLE hFind;   
    String  fullPath = filePath + extension;
    hFind = FindFirstFile(fullPath.c_str(), &fileInfo);
    if (hFind == INVALID_HANDLE_VALUE){return;} 
    else {
        return FileName.push_back(filePath+fileInfo.cFileName);
        while (FindNextFile(hFind, &fileInfo) != 0){
            return FileName.push_back(filePath+fileInfo.cFileName);}
        }
 }


 String optfileName ="";        
 String inputFolderPath =""; 
 String extension = "*.jpg*";
 getFilesList(inputFolderPath,extension,filesPaths);
 vector<string>::const_iterator it = filesPaths.begin();
 while( it != filesPaths.end())
 {
    frame = imread(*it);//read file names
            //doyourwork here ( frame );
    sprintf(buf, "%s/Out/%d.jpg", optfileName.c_str(),it->c_str());
    imwrite(buf,frame);   
    it++;
 }
{ WIN32_查找_数据文件信息; 处理高频风; 字符串fullPath=文件路径+扩展名; hFind=FindFirstFile(fullPath.c_str(),&fileInfo); 如果(hFind==无效的句柄值){return;} 否则{ 返回FileName.push_back(filePath+fileInfo.cFileName); while(FindNextFile(hFind,&fileInfo)!=0){ 返回FileName.push_bac
void getFilesList(String filePath,String extension, vector<string> & returnFileName)
{
    WIN32_FIND_DATA fileInfo;
    HANDLE hFind;   
    String  fullPath = filePath + extension;
    hFind = FindFirstFile(fullPath.c_str(), &fileInfo);
    if (hFind == INVALID_HANDLE_VALUE){return;} 
    else {
        return FileName.push_back(filePath+fileInfo.cFileName);
        while (FindNextFile(hFind, &fileInfo) != 0){
            return FileName.push_back(filePath+fileInfo.cFileName);}
        }
 }


 String optfileName ="";        
 String inputFolderPath =""; 
 String extension = "*.jpg*";
 getFilesList(inputFolderPath,extension,filesPaths);
 vector<string>::const_iterator it = filesPaths.begin();
 while( it != filesPaths.end())
 {
    frame = imread(*it);//read file names
            //doyourwork here ( frame );
    sprintf(buf, "%s/Out/%d.jpg", optfileName.c_str(),it->c_str());
    imwrite(buf,frame);   
    it++;
 }
CString dirpath="d:\\mydir"
DWORD errVal = ERROR_SUCCESS;
HANDLE dir;
WIN32_FIND_DATA file_data;
CString  file_name,full_file_name;
if ((dir = FindFirstFile((dirname+ "/*"), &file_data)) == INVALID_HANDLE_VALUE)
{
    errVal=ERROR_INVALID_ACCEL_HANDLE;
    return errVal;
}

while (FindNextFile(dir, &file_data)) {
    file_name = file_data.cFileName;
    full_file_name = dirname+ file_name;
    if (strcmp(file_data.cFileName, ".") != 0 && strcmp(file_data.cFileName, "..") != 0)
    {
        m_List.AddTail(full_file_name);
    }
}
#include <string>
#include <iostream>
#include <boost/filesystem.hpp>
using namespace std;
using namespace boost::filesystem;

int main()
{
    path p("D:/AnyFolder");
    for (auto i = directory_iterator(p); i != directory_iterator(); i++)
    {
        if (!is_directory(i->path())) //we eliminate directories in a list
        {
            cout << i->path().filename().string() << endl;
        }
        else
            continue;
    }
}
file1.txt
file2.dat
#include <atlstr.h>

void getFiles(CString directory) {
    HANDLE dir;
    WIN32_FIND_DATA file_data;
    CString  file_name, full_file_name;
    if ((dir = FindFirstFile((directory + "/*"), &file_data)) == INVALID_HANDLE_VALUE)
    {
        // Invalid directory
    }

    while (FindNextFile(dir, &file_data)) {
        file_name = file_data.cFileName;
        full_file_name = directory + file_name;
        if (strcmp(file_data.cFileName, ".") != 0 && strcmp(file_data.cFileName, "..") != 0)
        {
            std::string fileName = full_file_name.GetString();
            // Do stuff with fileName
        }
    }
}
getFiles("i:\\Folder1");
#include <dirent.h>

if (auto dir = opendir("some_dir/")) {
    while (auto f = readdir(dir)) {
        if (!f->d_name || f->d_name[0] == '.')
            continue; // Skip everything that starts with a dot

        printf("File: %s\n", f->d_name);
    }
    closedir(dir);
}