c++ 得到指定目录下指定文件名 windows vs2010

9 篇文章 0 订阅
1 篇文章 0 订阅

c++ 得到指定目录下指定文件名方法颇多,网上寻找总结有:

1. 主要思路是使用第三方库 dirent.h 文件来完成

C/C++ 获取目录下的文件列表信息

库文件下载点这里

数据结构:

struct dirent
{
    long d_ino;                 /* inode number 索引节点号 */
    off_t d_off;                /* offset to this dirent 在目录文件中的偏移 */
    unsigned short d_reclen;    /* length of this d_name 文件名长 */
    unsigned char d_type;        /* the type of d_name 文件类型 */    
    char d_name [NAME_MAX+1];   /* file name (null-terminated) 文件名,最长255字符 */
}
 
struct __dirstream
  {
    void *__fd;                        /* `struct hurd_fd' pointer for descriptor.  */
    char *__data;                /* Directory block.  */
    int __entry_data;                /* Entry number `__data' corresponds to.  */
    char *__ptr;                /* Current pointer into the block.  */
    int __entry_ptr;                /* Entry number `__ptr' corresponds to.  */
    size_t __allocation;        /* Space allocated for the block.  */
    size_t __size;                /* Total valid data in the block.  */
    __libc_lock_define (, __lock) /* Mutex lock for this structure.  */
  };

typedef struct __dirstream DIR;

stackoverflow示例

DIR *dir;
struct dirent *ent;
if ((dir = opendir ("c:\\src\\")) != NULL)
{
/* print all the files and directories within directory */
    while ((ent = readdir (dir)) != NULL)
    {
        printf ("%s\n", ent->d_name);
    }
    closedir (dir);
}
else
{
    /* could not open directory */
    perror ("");
    return EXIT_FAILURE;
}


博客示例

#include <sys/types.h>
#include <dirent.h>
#include <unistd.h>
#include <stdio.h>

int main(){
    DIR    *dir;
    struct    dirent    *ptr;
    dir = opendir("."); ///open the dir

    while((ptr = readdir(dir)) != NULL) ///read the list of this dir
    {
        #ifdef _WIN32
            printf("d_name: %s\n", ptr->d_name);
        #endif
        #ifdef __linux
            printf("d_type:%d d_name: %s\n", ptr->d_type,ptr->d_name);
        #endif
    }
    closedir(dir);
    return 0;
}


2. 主要思路是利用 boot filesystem module 来完成。如果是交叉平台上,最好的方法是使用库来完成。

以下摘自stackoverflow:

给定一个路径和文件名,以下函数迭代地在该目录和该目录下的子目录中搜索该文件,返回一个布尔值,和如果成功找到的文件的路径。

bool find_file( const path & dir_path,         // in this directory,
                const std::string & file_name, // search for this name,
                path & path_found )            // placing path here if found
{
  if ( !exists( dir_path ) ) return false;
  directory_iterator end_itr; // default construction yields past-the-end
  for ( directory_iterator itr( dir_path );
        itr != end_itr;
        ++itr )
  {
    if ( is_directory(itr->status()) )
    {
      if ( find_file( itr->path(), file_name, path_found ) ) return true;
    }
    else if ( itr->leaf() == file_name ) // see below
    {
      path_found = itr->path();
      return true;
    }
  }
  return false;
}


3. 主要思路是使用io.h提供的 handle_File =_findfirst( filespec, &fileinfo) 与 _findnext( handle_File, &fileinfo) 函数完成。

其中 handle_File 是文件句柄

filespec 是指定文件特性

fileinfo 是装有文件信息的结构体

函数名称:_findfirst
函数功能:搜索与指定的文件名称匹配的第一个实例,若成功则返回第一个实例的句柄,否则返回-1L
函数原型:long _findfirst( char *filespec, struct _finddata_t *fileinfo );
头文件:io.h


函数名称:_findnext

函数功能:搜索与_findfirst函数提供的文件名称匹配的下一个实例,若成功则返回0,否则返回-1

函数原型:int _findnext( intptr_t handle, struct _finddata_t *fileinfo);

头文件:io.h


程序举例(http://baike.baidu.com/view/1186290.htm)

#include<io.h>
#include<stdio.h>
int main()
{
    long Handle;
    struct _finddata_t FileInfo;
    if((Handle=_findfirst("D:\\*.txt",&FileInfo))==-1L)
        printf("没有找到匹配的项目\n");
    else
    {
        printf("%s\n",FileInfo.name);
        while(_findnext(Handle,&FileInfo)==0)
            printf("%s\n",FileInfo.name);
        _findclose(Handle);
    }
    return 0;
}

相关博客有:

使用_findfirst和_findnext遍历目录

Window文件目录遍历 和 WIN32_FIND_DATA 结构

使用C++获取文件夹中所有文件名(windows环境)

c++ 遍历目录下文件 该文将文件目录遍历封装成类

4. 一个函数就够,不需要三方库

函数如下:

#include <Windows.h>

vector<string> get_all_files_names_within_folder(string folder)
{
    vector<string> names;
    char search_path[200];
    sprintf(search_path, "%s*.*", folder.c_str());
    WIN32_FIND_DATA fd; 
    HANDLE hFind = ::FindFirstFile(search_path, &fd); 
    if(hFind != INVALID_HANDLE_VALUE) 
    { 
        do 
        { 
            // read all (real) files in current folder
            // , delete '!' read other 2 default folder . and ..
            if(! (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ) 
            {
                names.push_back(fd.cFileName);
            }
        }while(::FindNextFile(hFind, &fd)); 
        ::FindClose(hFind); 
    } 
    return names;
}

以上不少方法参见 此贴

实践过方法3,并简化为只访问指定目录下指定文件(不访问字目录):

#ifndef GETDIRECTORY_REDUCED_H
#define GETDIRECTORY_REDUCED_H

#include <stdlib.h>
#include <direct.h>
#include <string>
#include <io.h>

class CBrowseDir
{
private:
	char m_szDir[_MAX_PATH];
	int m_nFileCount;   //保存文件个数
	long int handle_File;

public:
	CBrowseDir();

	//设置初始目录为dir,指定文件filespec,如果返回false,表示目录不可用
	bool SetDir(const char *dir, const char *filespec);

	//遍历目录dir下由filespec指定的文件,不访问子目录,如果返回false,表示中止遍历文件
	bool BrowseDir(const char *filespec);

	//每次调用给出该目录下的下一个指定文件的路径,成功返回true
	bool CBrowseDir::NextFile(std::string &);

	//返回文件个数
	int GetFileCount();
};

#endif

#include <stdlib.h>
#include <direct.h>
#include <string>
#include <io.h>
#include <stdio.h>
#include <iostream>
#include "GetDirectory_Reduced.h"

using namespace std;

CBrowseDir::CBrowseDir()
{
	//用当前目录初始化m_szDir
	_getcwd(m_szDir,_MAX_PATH);

	//如果目录的最后一个字母不是'\',则在最后加上一个'\'
	int len=strlen(m_szDir);
	if (m_szDir[len-1] != '\\')
	{
		m_szDir[len]='\\';
		m_szDir[len+1]='\0';
	}//strcat(m_szDir,"\\");

	m_nFileCount=0;
}

bool CBrowseDir::SetDir(const char *dir, const char *filespec)
{
	//先把dir转换为绝对路径
	if (_fullpath(m_szDir,dir,_MAX_PATH) == NULL)
		return false;

	//判断目录是否存在,并转到指定目录m_szDir下
	if (_chdir(m_szDir) != 0)
		return false;

	//如果目录的最后一个字母不是'\',则在最后加上一个'\'
	int len=strlen(m_szDir);
	if (m_szDir[len-1] != '\\')
	{
		m_szDir[len]='\\';
		m_szDir[len+1]='\0';
	}//strcat(m_szDir,"\\");

	_chdir(m_szDir);//转换到指定目录下
	_finddata_t fileinfo;
	handle_File=_findfirst(filespec,&fileinfo);//首先查找dir中符合要求的文件
	if(handle_File==-1)
		return false;

	return true;
}

bool CBrowseDir::BrowseDir(const char *filespec)
{
	_chdir(m_szDir);

	//首先查找dir中符合要求的文件
	long hFile;
	_finddata_t fileinfo;
	if ((hFile=_findfirst(filespec,&fileinfo)) != -1)
	{
		do
		{
			//检查如果不是子文件夹,则进行处理
			if (!(fileinfo.attrib & _A_SUBDIR))
			{
				string filename(m_szDir);//用string来处理,避免strcpy、strcat带来的warning
				filename+=fileinfo.name;
				cout << filename << endl;
				m_nFileCount++;//文件数加1
			}
		} while (_findnext(hFile,&fileinfo) == 0);
		_findclose(hFile);
	}
	return true;
}

bool CBrowseDir::NextFile(string &nextfilename)
{
	_finddata_t fileinfo;
	while(_findnext(handle_File,&fileinfo) == 0)
	{
		//检查如果不是子文件夹,则进行处理
		if((fileinfo.attrib & _A_SUBDIR))
			continue;
		string filename(m_szDir);//用string来处理,避免strcpy、strcat带来的warning
		filename+=fileinfo.name;
		cout << filename << endl;
		nextfilename=filename;
		m_nFileCount++;//文件数加1
		return true;
	}
	_findclose(handle_File);
	return false;
}

//返回文件个数
int CBrowseDir::GetFileCount()
{
	return m_nFileCount;
}


在Linux系统中,可以使用标准库函数 `open` 和 `read`、`write`、`close` 等函数来进行文件的读取和写入操作。具体操作步骤如下: 1. 打开源文件和目标文件。 使用 `open` 函数打开源文件和目标文件,需要指定打开文件的路径和打开方式。例如: ```c int fd_src = open("source.txt", O_RDONLY); // 只读方式打开源文件 int fd_dest = open("destination.txt", O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR); // 读写方式打开或创建目标文件 ``` 2. 读取源文件中的内容。 使用 `read` 函数从源文件中读取数据,需要指定读取的数据块大小和读取的数据块数量。例如: ```c char buffer[1024]; // 缓冲区 ssize_t count; // 实际读取的数据块数量 do { count = read(fd_src, buffer, sizeof(buffer)); write(fd_dest, buffer, count); } while (count > 0); ``` 上述代码中,每次读取 `sizeof(buffer)` 个字符到缓冲区 `buffer` 中,然后将缓冲区中的内容写入目标文件中。 3. 关闭文件。 使用 `close` 函数关闭源文件和目标文件,释放文件资源。例如: ```c close(fd_src); close(fd_dest); ``` 完整代码示例: ```c #include <stdio.h> #include <fcntl.h> #include <unistd.h> #include <sys/stat.h> int main() { int fd_src = open("source.txt", O_RDONLY); int fd_dest = open("destination.txt", O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR); char buffer[1024]; ssize_t count; do { count = read(fd_src, buffer, sizeof(buffer)); write(fd_dest, buffer, count); } while (count > 0); close(fd_src); close(fd_dest); return 0; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值