gpt4 book ai didi

C++读取添加到目录的新文件

转载 作者:行者123 更新时间:2023-11-30 05:07:57 27 4
gpt4 key购买 nike

我有一个 C++ 程序,它在启动时获取目录中所有文件的列表并对它们进行一些处理(将它们打包以便通过网络传输)。当前版本是静态的,程序只能在程序启动时看到文件。现在我想将它更改为动态版本,它可以连续看到目录中添加的新文件(假设它们有一个有意义的递增名称;例如 f1、f2、f3,...所以下一个将是 f4 . 这样我就可以使用一些索引了)。

现在这是一段代码(静态读取所有文件):

DIR *dp;
struct dirent *dirp;
char * dir = new char[inData->dir.length() + 1];
strcpy(dir, inData->dir.c_str());
dp = opendir(dir);
int file_index = 0;
int total_files = DataUtil::count_files(dp);

if (readdir(dp) == NULL)
rewinddir(dp);

//for each file in the directory
while ((dirp = readdir( dp ))) {
string f_name = dirp->d_name;
if (f_name != "." && f_name != "..") { // except . and ..
//Do some processing
my_function(f_name, file_index);
file_index++;
}
}
closedir(dp);

我使用 rewinddir(dp); 函数和 file_index 修改了代码以注意到新文件。但它不起作用。问题出在哪里?

DIR *dp;
struct dirent *dirp;
char * dir = new char[inData->dir.length() + 1];
strcpy(dir, inData->dir.c_str());
dp = opendir(dir);
int file_index = 0;
int total_files = MyDataUtil::count_files(dp);

if (readdir(dp) == NULL)
rewinddir(dp);

//for each file in the directory
while ((dirp = readdir( dp ))) {
string f_name = dirp->d_name;
if (f_name != "." && f_name != "..") {
//skip files already read
for (int var = 0; var < file_index; var++) {
readdir(dp);
}
//Do some processing
my_function(f_name, file_index);
file_index++;

//reset dir stream, and update total_files
rewinddir(dp);
total_files = MyDataUtil::count_files(dp);
}
}
closedir(dp);

total_files 函数:

int MyDataUtil::count_files(DIR *dp){
struct dirent *dirp;
int num = 0;

while ((dirp = readdir( dp ))) {
string f_name = dirp->d_name;
if (f_name != "." && f_name != "..")
num++;
}
return num;
}

这是rewinddir 文档。它说“可能会或可能不会被退回”!

Description:

The rewinddir function is used to reinitialize the directory stream dirstream, so that if you call readdir
it returns information about the first entry in the directory again. This function also notices if files
have been added or removed to the directory since it was opened with opendir. (Entries for these files
might or might not be returned by readdir if they were added or removed since you last called opendir
or rewinddir.)

最佳答案

在您选择的目录中添加/删除/更改文件时,在 Linux 上使用 inotify 获取异步通知 http://man7.org/linux/man-pages/man7/inotify.7.html

关于C++读取添加到目录的新文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47063467/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com