c - 如何使用 c 中的目录打印同月修改的文件?

标签 c file date directory

<分区>

我正在编写一个代码,它获取其中包含 txt 文件的文件夹的目录,然后打印出创建/上次修改同一月份的所有 txt 文件。

例如,如果用户键入“JANUARY”,程序将打印出在一月份创建/最后修改的所有文件的名称。

这是我的代码,但它不起作用。

DIR *da; 
struct dirent *ep;  
struct stat attrib;  

da = opendir ("./"); 
if (da != NULL)  
{
    while (ep = readdir (da)) 
    {
    while ((ep = readdir (da)) != NULL) 
    {
        const size_t len = strlen(ep->d_name);    

            if (len > 4                    && 
            ep->d_name[len - 4] == '.' &&
            ep->d_name[len - 3] == 'T' &&
            ep->d_name[len - 2] == 'X' &&
            ep->d_name[len - 1] == 'T') {

                stat(ep->d_name, &attrib); 

                strftime(month, MAX_SIZE, "%m", localtime(&(attrib.st_ctime)));

                comp = strcmp(month,input);
                if(comp == 0) {
                    printf ("%s\n", ep->d_name);
                }   
            } 
       } 
    closedir (da);
    }    
} 

最佳答案

您在错误的位置关闭了目录流。您正在内部 while 中关闭它,但您必须在外部 while 之后关闭它。

if (da != NULL) 
{
 while (ep = readdir (da)) 
   while ((ep = readdir (da)) != NULL)
   {
    const size_t len = strlen(ep->d_name);   

    if (len > 4                    &&
        ep->d_name[len - 4] == '.' &&
        ep->d_name[len - 3] == 't' &&
        ep->d_name[len - 2] == 'x' &&
        ep->d_name[len - 1] == 't') {

            stat(ep->d_name, &attrib); 
            foo = localtime(&(attrib.st_mtime));

            if(foo->tm_mon+1 == 1) {


             printf ("%s\n", ep->d_name);
                }
        }
   }
 closedir (da); 
}

之后,在检查 if 中的条件时,您可以使用 strcmp 函数。

int strcmp(const char *s1, const char *s2);

if ( strcmp(ep->d_name+(len-4),".txt") ==0 ){ 
...
}

关于c - 如何使用 c 中的目录打印同月修改的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27717655/

相关文章:

c - 在 Vala 中继承接口(interface) - 与基本方法不兼容

c - 删除文件中的记录(C语言编程)

c++ - 使用重新解释转换将结构或类保存到文件

javascript - 在 JavaScript 中解析日期时得到错误的结果

python sql查询列表中的时间戳

delphi - 在 Delphi 中将 TDateTime 声明为 Const

字符 ch[] ="some string";

将结构数组的索引与 NULL 进行比较,而不是评估为 true;

c++ - 对于完整的 c 和 c++ 编译器,我应该在 MinGW 设置中选择哪些选项

c# - 如何从回收站中恢复文件