2011-04-26 80 views
0

我想从目录中只读取.txt文件。 我没有使用数组。 我正在使用opendir()来打开我的目录。 d->d_name列出了我所有的文件和子文件夹。 我想只读.txt但不是子文件夹。从子目录中只能读取.txt文件

请帮帮我。 谢谢

回答

1

你不能用FindFirstFileFindNextFile这个吗?

+0

这将取决于他编程的平台。 opendir/readdir函数有点更便携。 – 2011-04-26 20:17:45

+0

我实际上只是想问问他是否知道其他两种方法的存在,如果他只是针对Windows进行开发,那么这种方法非常简单。如果他需要可移植性,那么我同意你:)。 – 2011-04-26 20:25:36

0

你可以尝试把文件名成简单的结构(字符串数组或例如向量),然后传递到结构上修剪不使用中的.txt扩展

名称的函数的引用函数,查看每个文件名(一个for循环会很方便),并使用String库中的find函数来查看最后四个字符是否为== to .txt。您可以重置位置以开始将字符串搜索到string_name.length - 4,以便您只比较最后几个字符。

Cplusplus.com是搞什么的字符串库有很大的参考:http://www.cplusplus.com/reference/string/string/find/

+0

其实,@Riccardo Tramma下面的建议比较好,我想。 – Joe 2011-04-26 20:18:48

1

嗯,是这样的:

  • 调用执行opendir()打开目录,在一个循环
  • ,通话readdir读取每个条目
  • 每个条目,检查的名字,看看最后4个字符是“.TXT”
  • 如果是这样,做somethi您struct dirent代表NG
  • 末,调用closedir来关闭目录
1

可以使用stat()函数来确定文件的类型。

struct stat sb; 
int rc = stat(filename, &sb); 
// error handling if stat failed 
if (S_ISREG(sb.st_mode)) { 
// it's a regular file, process it 
} else { 
// it's not a regular file, skip it 
} 

有关详细信息,请阅读手册页。还要注意d_name中的文件名不包含目录部分。如果您所在的目录不是opendir',那么您需要预先安装目录名称(如果需要,还需要目录分隔符)。请参阅boost::filesystem

0

假设您在Linux/Posix系统上,您可以使用scandir(...)。您可以在手册页上找到详细信息,但是总之,您必须提供一个筛选器函数,该函数将指针作为参数,并且如果要包含条目,则返回非零值(对于您的情况,您会检查以.txt结尾的名称,以及可能的dirent结构中的文件类型)。

0
#include <stdio.h> 
#include <sys/types.h> 
#include <dirent.h> 
#include <errno.h> 

int main(int argc, char *argv[]) 
{ 
    DIR *dir; 

    struct dirent *entry; 

    int pos; 

    if (argc < 2) 
    { 
     printf("Usage: %s <directory>\n", argv[0]); 
     return 1; 
    } 

    if ((dir = opendir(argv[1])) == NULL) 
    { 
     perror("opendir"); 
     return 1; 
    } 

    while ((entry = readdir(dir)) != NULL) 
    { 
     if (entry->d_type != DT_REG) 
      continue; 

     pos = strlen(entry->d_name) - 4; 

     if (! strcmp(&entry->d_name[pos], ".txt")) 
     { 
      printf("%s\n", entry->d_name); 
     } 
    } 

    if (closedir(dir) == -1) 
    { 
     perror("closedir"); 
     return 1; 
    } 

    return 0; 
}