我有能力列出给定目录中的文件,但是我想隔离在目录中找到的每个文件,然后读取下一个文件,然后对其进行一些操作(例如更改其名称)。
我只是想知道如何监视目录(以便函数不会结束,而是列出添加到目录中的文件),以及上面的内容以按找到的顺序对每个文件执行某些操作。
int main(void)
{
struct dirent* de; // Pointer for directory entry
// opendir() returns a pointer of DIR type.
DIR* dr = opendir("E:\\Users\\Joe\\Downloads");
if (dr == NULL) // opendir returns NULL if couldn't open directory
{
printf("Could not open current directory");
return 0;
}
// Refer http://pubs.opengroup.org/onlinepubs/7990989775/xsh/readdir.html
// for readdir()
while ((de = readdir(dr)) != NULL)
printf("%s\n", de->d_name);
closedir(dr);
return 0;
}
如果有任何 Windows 特定的方法可以做到这一点,我会很感激一个例子,因为我非常努力地创建自己的方法。先感谢您。
FindFirstFile()
并且FindNextFile()
是 Windows 特定的方法来做你想做的事......
在此示例的以下改编中,我已经评论了可以找到的文件名的位置。(即名称已更改、打开/编辑等)查找“//// 在这里工作...”。
在命令行上输入目录路径,例如C:\\dir1\\dir2
,这将找到该位置的所有文件。
请注意,此改编删除了一些用于复制和连接字符串的愚蠢的 Microsoft 方法。
#define MAX_PATHNAME_LEN 260
int main(int argc, char *argv[])
{
WIN32_FIND_DATA FindFileData;
HANDLE hFind = INVALID_HANDLE_VALUE;
DWORD dwError;
char DirSpec[MAX_PATHNAME_LEN];
size_t length_of_arg;
// Check for command-line parameter; otherwise, print usage.
if(argc != 2)
{
printf("Usage: Test <dir>\n");
return 2;
}
// Check that the input is not larger than allowed.
length_of_arg = strlen(argv[1]);
if (length_of_arg > (MAX_PATHNAME_LEN - 2))
{
printf("Input directory is too large.\n");
return 3;
}
printf ("Target directory is %s.\n", argv[1]);
// Prepare string for use with FindFile functions. First,
// copy the string to a buffer, then append '\*' to the
// directory name.
sprintf(DirSpec, "%s\\*", argv[1]);
// Find the first file in the directory.
hFind = FindFirstFile(DirSpec, &FindFileData);
if (hFind == INVALID_HANDLE_VALUE)
{
printf ("Invalid file handle. Error is %u.\n", GetLastError());
return (-1);
}
else
{
printf ("First file name is %s.\n", FindFileData.cFileName); "/// do your work here..."
// List all the other files in the directory.
while (FindNextFile(hFind, &FindFileData) != 0)
{
printf ("Next file name is %s.\n", FindFileData.cFileName); "/// do your work here..."
}
dwError = GetLastError();
FindClose(hFind);
if (dwError != ERROR_NO_MORE_FILES)
{
printf ("FindNextFile error. Error is %u.\n", dwError);
return (-1);
}
}
return (0);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句