C语言实现文件查找操作
在文件操作过程中,免不得要去查找文件之类的。虽然说Windows的API提供了不少这样的接口,但是还是比较倾向于C和C++之类的库。以下就用例子来做这样的工作,程序本身当然还有不少不成熟之处,编译工具用的是Dev C++,编译环境建立在WindowsXP上。
#include <iostream>
#include <string.h>
#include <dir.h>
using namespace std;
int main(int argc, char *argv[])
{
struct _finddata_t myfile;
char path[256];
char extension[20];
printf("Please input the extension of the file: ");
scanf("%s", extension);
sprintf(path, "D:\\Work\\*.%s", extension);
printf("List of the .%s files:\n", extension);
long done = _findfirst(path,&myfile);
int find=0;
while (!find)
{
if (strcmp(myfile.name, ".") && strcmp(myfile.name, ".."))
printf("%s\n",myfile.name);
find=_findnext(done,&myfile);
}
_findclose(done);
system("PAUSE");
return 0;
}
如果是在Linux环境下运行,可能会提示找不到dir.h文件,所以还是在Windows下编译运行吧。下面给一个列出文件目录下所有文件的程序,可以在Windows和Linux都能运行。
int main()
{
DIR * dir;
struct dirent * ptr;
int i;
dir = opendir("D:\\Work\\");
while(ptr = readdir(dir)) {
printf("file name: %s\n", ptr->d_name;
}
closedir(dir);
}
以上这个参考过别人的程序,大家如果有更多的指教请多多指出。
原创文章,如需转载请注明【转烛空间】:http://wangliping.net
久违的C语言啊。就上学时学了点皮毛。。