开发者

While parsing into a root folder how can I distinguish the upcoming is whether a file or a folder in C language?

I want to parse through a root folder which is entered by the user by using multi threading and multi processing at different versions.But how can I distinguish while I am parsing through a r开发者_StackOverflow中文版oot folder whether the next is a folder or a file?To summarize I want to learn how I can distinguish the upcoming is a file or a folder.I wanna learn this because if it is a folder then I let opening this folder to a dynamically thread and/or process.If it is a file the existing thread or process can continue its work without any necessarity to create any different thread and/or process.I hope I can express my problem.I am waiting your answers.Thank you.


You can check whether a path refers to a file or directory using the stat() function, and checking the st_mode field on the returned structure (see http://pubs.opengroup.org/onlinepubs/009695399/basedefs/sys/stat.h.html).

On Windows, you can use GetFileAttributesEx to get the file attributes, which you can check to see if it is a file or a directory.

Note that whatever you use may be subject to a race condition if the file system is being updated by another thread or process at the same time, as the file/directory may be deleted and/or changed after you checked it and before you access it.


Here are some quick samples. It will be up to you to thread from multiple root locations, call these recursively, and sync all the data.

Under *nix systems;

struct dirent *entry;
while ((entry = readdir("/root")) != NULL)
{
   if (entry->d_type == DT_DIR)
   {
      // do something
   }
}
closedir(dir);

Under Windows:

WIN32_FIND_DATA findData;
HANDLE hFind = FindFirstFile(("C:\\root" + "*.*").c_str(), &findData);
do
{
   if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
   {
      // do something
   }

} while (FindNextFile(hFind, &findData));

FindClose(hFind);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜