[英]Reading txt files in a choosen directory
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
int main (void)
{
DIR *dp;
struct dirent *ep;
dp = opendir ("./");
if (dp != NULL)
{
while (ep = readdir (dp))
puts (ep->d_name);
(void) closedir (dp);
}
else
perror ("Couldn't open the directory");
return 0;
}
这段代码为我提供了该目录中的所有内容。 它的工作方式类似于“ ls”命令。 例如,假设我在该目录中有一个名为name的文件夹,而一个名为.input的.txt文件(名称可能不同)。 我想确定是文件夹还是txt文件。如果是txt文件,我该如何阅读?
]您可以使用scandir()
函数打开并扫描目录中的条目。
该示例来自man 3 scandir
#define _SVID_SOURCE
/* print files in current directory in reverse order */
#include <dirent.h>
int
main(void)
{
struct dirent **namelist;
int n;
n = scandir(".", &namelist, NULL, alphasort);
if (n < 0)
perror("scandir");
else {
while (n--) {
printf("%s\n", namelist[n]->d_name);
free(namelist[n]);
}
free(namelist);
}
}
注意struct dirent
:
struct dirent {
ino_t d_ino; /* inode number */
off_t d_off; /* offset to the next dirent */
unsigned short d_reclen; /* length of this record */
unsigned char d_type; /* type of file; not supported
by all file system types */
char d_name[256]; /* filename */
};
您可以通过d_type
字段检查当前条目是否为常规文件,目录或其他文件。
可用的文件类型为:
#define DT_UNKNOWN 0
#define DT_FIFO 1
#define DT_CHR 2
#define DT_DIR 4 // directory type
#define DT_BLK 6
#define DT_REG 8 // regular file, txt file is a regular file
#define DT_LNK 10
#define DT_SOCK 12
#define DT_WHT 14
检查文件的名称和类型后,可以使用open()
(系统调用)或fopen()
(glib函数)安全地打开它,并通过read()
读取内容(如果通过open()或fread()
(与fopen()对应)。
阅读后不要忘记关闭文件。
此外,如果只想检查目录的存在和可访问性,则access()
。
下面的代码测试dir是否存在。
int exist_dir (const char *dir)
{
DIR *dirptr;
if (access(dir, F_OK) != -1) {
// file exists
if ((dirptr = opendir(dir)) != NULL) {
// do something here
closedir (dirptr);
} else {
// dir exists, but not a directory
return -1;
}
} else {
// dir does not exist
return -1;
}
return 0;
}
除内容外,有关文件的所有信息都可以通过调用stat
函数获得。 stat
有签名
int stat(const char *pathname, struct stat *buf);
并在buf
的缓冲区中返回有关文件的信息。
struct stat
在字段st_mode
编码文件类型和文件许可权的st_mode
。
定义了一些其他宏来测试文件类型:
S_ISREG(m)是常规文件吗?
S_ISDIR(m)目录?
S_ISCHR(m)字符设备?
S_ISBLK(m)块设备?
S_ISFIFO(m)FIFO(命名管道)?
S_ISLNK(m)符号链接? (不在POSIX.1-1996中。)
S_ISSOCK(m)插座? (不在POSIX.1-1996中。)
这是一段示例代码:
stat(pathname, &sb);
if (S_ISREG(sb.st_mode)) {
/* Handle regular file */
}
至于读取,请使用sprintf
函数将目录路径和文件名连接起来以获取文件路径,如下所示:
sprintf(file_path, "%s/%s", dir_path, file_name);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.