您的位置:首页 > 其它

文件操作两个小例子(zt)

2010-04-16 10:17 351 查看
#include <sys/types.h>
#include <dirent.h>
#include <stdio.h>

int main( int argc,char *argv[] )
{
DIR   *dp;
struct dirent *dirp;
if( argc != 2 )
{
printf("error:need argument!/n");
return 0;
}
if ( ( dp = opendir(argv[1]) ) == NULL )
{
printf("can't open dir %s/n",argv[1] );
return 0;
}
while ( (dirp = readdir (dp)) != NULL )
{
printf("%s/n",dirp->d_name);
}
closedir(dp);
return 0;
}


void FindFile(char * pFilePath)
{
WIN32_FIND_DATA FindFileData;
HANDLE hFind = INVALID_HANDLE_VALUE;
char DirSpec[MAX_PATH + 1];// 指定路径
DWORD dwError;

strncpy (DirSpec, pFilePath, strlen(pFilePath) + 1);
strncat (DirSpec, "/*", 3);

hFind = FindFirstFile((DirSpec, &FindFileData);

if (hFind == INVALID_HANDLE_VALUE)
{
printf ("Invalid file handle. Error is %u ", GetLastError());
return ;
}
else
{
if (FindFileData.dwFileAttributes != FILE_ATTRIBUTE_DIRECTORY )
{
printf ("  %s ", FindFileData.cFileName);   //找到文件
}
else if(FindFileData.dwFileAttributes == FILE_ATTRIBUTE_DIRECTORY
&& strcmp(FindFileData.cFileName, ".") != 0
&& strcmp(FindFileData.cFileName, "..") != 0)
{   //找到目录
char Dir[MAX_PATH + 1];
strcpy(Dir, pFilePath);
strncat(Dir, "/", 2);
strcat(Dir, FindFileData.cFileName);

FindFile(Dir);
}

while (FindNextFile(hFind, &FindFileData) != 0)
{
if (FindFileData.dwFileAttributes != FILE_ATTRIBUTE_DIRECTORY)
{   //找到文件
printf ("  %s ", FindFileData.cFileName);
}
else if(FindFileData.dwFileAttributes == FILE_ATTRIBUTE_DIRECTORY
&& strcmp(FindFileData.cFileName, ".") != 0
&& strcmp(FindFileData.cFileName, "..") != 0)
{ //找到目录
char Dir[MAX_PATH + 1];
strcpy(Dir, pFilePath);
strncat(Dir, "/", 2);
strcat(Dir, FindFileData.cFileName);
FindFile(Dir);
}

}

dwError = GetLastError();
FindClose(hFind);
if (dwError != ERROR_NO_MORE_FILES)
{
printf ("FindNextFile error. Error is %u ", dwError);
return;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: