我正在尝试创建一个函数来扫描我的 Windows PC 上的文件夹,每次扫描时,一个名为“Filter.txt”的文件都会附加字符串“Test Script”。
现在的问题是 2,第一个是必须在目录 c:\LOG 或其子目录中执行扫描,第二个是我不知道如何链接 fopen
在目录和文件名中。
int main(){
DIR *dir;
FILE * pFile;
char myString[100];
struct dirent *ent;
dir = opendir ("c:\\LOG");
if (dir != NULL) {
/* print all the files and directories */
while ((ent = readdir (dir)) != NULL) {
pFile = fopen ("Filter.txt","a");
if (pFile==NULL)
perror("Error");
else
fprintf(pFile,"%s\n","Test scriptIno");
fclose(pFile);
//printf ("%s\n", ent->d_name);
}
closedir (dir);
} else {
/* Can not open directory */
perror ("");
return EXIT_FAILURE;
}
}
最佳答案
关于如何将调用链接到 opendir
,您可以在 SO 上找到大量答案,例如 this .使用 ent->d_type
检查条目是目录还是文件。
要打开目录中的文件,只需使用 ent->d_name
中的路径名来构造 fopen
调用的路径。
编辑 工作有点无聊,做了一个你可能想要的功能...
#ifdef _WIN32
# define DIR_SEPARATOR "\\"
#else
# define DIR_SEPARATOR "/"
#endif
void my_readdir(const char *path)
{
DIR *dir = opendir(path);
if (dir != NULL)
{
struct dirent *ent;
static const char filtername[] = "filter.txt";
/* +2: One for directory separator, one for string terminator */
char *filename = (char *) malloc(strlen(path) + strlen(filtername) + 2);
strcpy(filename, path);
strcat(filename, DIR_SEPARATOR);
strcat(filename, filtername);
FILE *fp = fopen(filename, "a");
while ((ent = readdir(dir)) != NULL)
{
if (ent->d_type == DT_REG || ent->d_type == DT_DIR)
{
if (strcmp(ent->d_name, "..") != 0 && strcmp(ent->d_name, ".") != 0)
{
if (fp != NULL)
fprintf(fp, "%s : %s\n", (ent->d_type == DT_REG ? "File" : "Directory"), ent->d_name);
if (ent->d_type == DT_DIR)
{
/* +2: One for directory separator, one for string terminator */
char *newpath = (char *) malloc(strlen(path) + strlen(ent->d_name) + 2);
strcpy(newpath, path);
strcat(newpath, DIR_SEPARATOR);
strcat(newpath, ent->d_name);
/* Call myself recusively */
my_readdir(newpath);
free(newpath);
}
}
}
}
if (fp != NULL)
fclose(fp);
free(filename);
}
}
编辑 opendir
和readdir
函数似乎在 Windows 上没有得到很好的支持。以与我上面的示例类似的方式使用仅限 Windows 的 FindFirstFile
和 FindNextFile
。参见 this MSDN page有关如何使用这些功能的示例。
关于c - 扫描目录并修改c中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8152056/