如何确定文件夹是否存在以及如何创建文件夹? [英] How to find out if a folder exists and how to create a folder?

查看:123
本文介绍了如何确定文件夹是否存在以及如何创建文件夹?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要创建一个文件夹(如果它不存在)。我使用Windows,我对在其他平台上工作的代码不感兴趣。

I'm trying to create a folder if it doesn't exist. I'm using Windows and I am not interested on my code working in other platforms.

没关系,我找到了解决方案。我只是有一个包含的问题。答案是:

Never mind, I found the solution. I was just having a inclusion problem. The answer is:

#include <io.h>   // For access().
#include <sys/types.h>  // For stat().
#include <sys/stat.h>   // For stat().
#include <iostream>
#include <string>
using namespace std;

string strPath;
   cout << "Enter directory to check: ";
   cin >> strPath;

   if ( access( strPath.c_str(), 0 ) == 0 )
   {
      struct stat status;
      stat( strPath.c_str(), &status );

      if ( status.st_mode & S_IFDIR )
      {
         cout << "The directory exists." << endl;
      }
      else
      {
         cout << "The path you entered is a file." << endl;
      }
   }
   else
   {
      cout << "Path doesn't exist." << endl;
   }


推荐答案

POSIX兼容通话 mkdir 。当该目录已存在时, It 会自动失败。

The POSIX-compatible call is mkdir. It silently fails when the directory already exists.

如果您使用的是Windows API,请 CreateDirectory 更合适。

If you are using the Windows API, then CreateDirectory is more appropriate.

这篇关于如何确定文件夹是否存在以及如何创建文件夹?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆