1. 程式人生 > >linux在指定目錄下建立資料夾的c語言實現

linux在指定目錄下建立資料夾的c語言實現

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sys/types.h>
#include <errno.h>

#define MAX_DIRPATH_LEN 512
#define DEFAULT_DIRPATH "Hello world"

static char dirpath[MAX_DIRPATH_LEN];

//沒有用到這段程式,不過如果想建立一個檔名的完整路徑可以執行這個函式
const char* filename_to_full_path(char* filename)
{
    static char buf[1024];
    sprintf(buf, "%s/%s", dirpath, filename);
    return buf;
}

int main (int argc , char** argv)
{
    struct stat file_stat;
    int ret;

    //下面語句是建立預設資料夾的路徑
    strncpy(dirpath, getenv("HOME"), MAX_DIRPATH_LEN);//預設的路徑為home
    dirpath[ strlen(dirpath) ] = '/';//新增分隔符
    strncpy(dirpath + strlen(dirpath), DEFAULT_DIRPATH, MAX_DIRPATH_LEN - strlen(dirpath));//預設的資料夾

    argc--;

    if(argc)
    {
        if(!argv[1])
        {
            printf("the argument is invalue!\n");
            return -1;
        }
        strcpy(dirpath, argv[1]);//執行程式時可以輸入自己想建立的資料夾的完整路徑
    }
    
    ret = stat(dirpath, &file_stat);//檢查資料夾狀態
    if(ret<0)
    {
        if(errno == ENOENT)//是否已經存在該資料夾
        {
            ret = mkdir(dirpath, 0775);//建立資料夾
            printf("creat dir '/%s'/\n", dirpath);
            if(ret < 0)
            {
                printf("Could not create directory \'%s\' \n",
					dirpath);
				return EXIT_FAILURE;
            }

        }
        else
        {
            printf("bad file path\n");
            return EXIT_FAILURE;
        }
    }

}

以上程式碼完成的功能是在linux下建立資料夾,預設路徑是home下,預設資料夾名是在Hello world

在執行程式時可以帶引數執行,引數為要建立資料夾的完整路徑

上面用到一些函式或變數如:struct stat、stat()、mkdir()、errno等,都可以在網上查到

其中函式const char * filename_to_full_path(char* filename)在程式中沒有使用,不過如果想在新建的資料夾中建立新檔案的話,可以呼叫那個函式,生成檔案的完整路徑之後,在呼叫檔案操作函式即可。