博客專欄

EEPW首頁 > 博客 > linux下使用c語言刪除指定目錄下所有文件

linux下使用c語言刪除指定目錄下所有文件

發(fā)布人:電子禪石 時(shí)間:2020-09-14 來源:工程師 發(fā)布文章
我一直以為使用c提供的方法可以跨越平臺(tái),但無疑我是錯(cuò)的,上次寫的刪除文件所使用的兩個(gè)api——_findfirst和_findnext無法在gcc下使用,但linux下有opendir和readdir來代替。復(fù)制內(nèi)容到剪貼板
代碼:
/
//Name:           DeleteFile
//Purpose:        Delete file in the special directory
//Author:         Alex Wang
//Created:        2011-12-01
//Copy right:
//Licence:
//

#ifndef _DELETE_FILE
#define _DELETE_FILE
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>
#include <dirent.h>
#include <limits.h>
#include <string.h>
#include <stdio.h>
#include <limits.h>

//判斷是否為目錄
bool is_dir(const char *path)
{
    struct stat statbuf;
    if(lstat(path, &statbuf) ==0)//lstat返回文件的信息,文件信息存放在stat結(jié)構(gòu)中
    {
        return S_ISDIR(statbuf.st_mode) != 0;//S_ISDIR宏,判斷文件類型是否為目錄
    }
    return false;
}

//判斷是否為常規(guī)文件
bool is_file(const char *path)
{
    struct stat statbuf;
    if(lstat(path, &statbuf) ==0)
        return S_ISREG(statbuf.st_mode) != 0;//判斷文件是否為常規(guī)文件
    return false;
}

//判斷是否是特殊目錄
bool is_special_dir(const char *path)
{
    return strcmp(path, ".") == 0 || strcmp(path, "..") == 0;
}

//生成完整的文件路徑
void get_file_path(const char *path, const char *file_name,  char *file_path)
{
    strcpy(file_path, path);
    if(file_path[strlen(path) - 1] != '/')
        strcat(file_path, "/");
    strcat(file_path, file_name);
}

void delete_file(const char *path)
{
    DIR *dir;
    dirent *dir_info;
    char file_path[PATH_MAX];
    if(is_file(path))
    {
        remove(path);
        return;
    }
    if(is_dir(path))
    {
        if((dir = opendir(path)) == NULL)
            return;
        while((dir_info = readdir(dir)) != NULL)
        {
            get_file_path(path, dir_info->d_name, file_path);
            if(is_special_dir(dir_info->d_name))
                continue;
            delete_file(file_path);
            rmdir(file_path);
        }
    }
}
int main(int argc, char **argv)
{
    delete_file("/home/AlexWang/test");
    return 0;
}
#endif


*博客內(nèi)容為網(wǎng)友個(gè)人發(fā)布,僅代表博主個(gè)人觀點(diǎn),如有侵權(quán)請(qǐng)聯(lián)系工作人員刪除。

隔離器相關(guān)文章:隔離器原理


關(guān)鍵詞:

相關(guān)推薦

技術(shù)專區(qū)

關(guān)閉