24

/tmpフォルダの内容を削除するプログラムを作成しようとしています。LinuxでC/C++を使用しています。

system("exec rm -r /tmp")

フォルダ内のすべてを削除しますが、不要なフォルダも削除します。

system();を介して呼び出されるある種のbashスクリプトによってこれを行う方法はありますか?または、C / C ++でこれを行う直接的な方法はありますか?

私の質問はこれに似ていますが、OS Xではありません...フォルダ内のすべてのファイルを削除する方法ですが、フォルダ自体は削除しませんか?

4

8 に答える 8

51
#include <stdio.h>
#include <dirent.h>

int main()
{
    // These are data types defined in the "dirent" header
    DIR *theFolder = opendir("path/of/folder");
    struct dirent *next_file;
    char filepath[256];

    while ( (next_file = readdir(theFolder)) != NULL )
    {
        // build the path for each file in the folder
        sprintf(filepath, "%s/%s", "path/of/folder", next_file->d_name);
        remove(filepath);
    }
    closedir(theFolder);
    return 0;
}

を介して、またはそのようなものを介して新しいシェルを生成する必要はありません。これはsystem()、非常に単純なことを行うための多くのオーバーヘッドであり、システムで利用可能なものについて不必要な仮定(および依存関係)を作成します。

于 2012-06-13T02:47:45.390 に答える
15

C / C ++では、次のことができます。

system("exec rm -r /tmp/*")

Bashでは、次のことができます。

rm -r /tmp/*

これにより、/ tmp内のすべてが削除されますが、/tmp自体は削除されません。

于 2012-06-13T02:36:12.883 に答える
3

ワイルドカード文字を使用することにより*、任意のタイプの拡張子を持つすべてのファイルを削除できます。

system("exec rm -r /tmp/*")

于 2012-06-13T02:35:48.610 に答える
3

できるよ

system("exec find /tmp -mindepth 1 -exec rm {} ';'");
于 2012-06-13T02:36:57.850 に答える
2

C / C ++では、次のものを使用できます(隠しディレクトリを含む)。

system("rm -r /tmp/* /tmp/.*");
system("find /tmp -mindepth 1 -delete");

しかし、「rm」または「find」ユーティリティがshに使用できない場合は、「ftw」および「remove」を使用することをお勧めします。

#define _XOPEN_SOURCE 500
#include <ftw.h>

static int remove_cb(const char *fpath, const struct stat *sb, int typeFlag, struct FTW *ftwbuf)
{
    if (ftwbuf->level)
        remove(fpath);
    return 0;
}

int main(void)
{
    nftw("./dir", remove_cb,  10, FTW_DEPTH);
    return 0;
}
于 2016-03-02T21:31:29.213 に答える
2

これは非常に古い質問だと思いますが、Demitriのすばらしい答えに基づいて、必要に応じてサブフォルダー内のファイルを再帰的に削除する関数を作成しました。

また、errnoを返すという点で、エラー処理も行います。関数ヘッダーは、doxygenによる解析用に作成されています。この関数は、私が使用した単純な例の場合に機能し、隠しフォルダーと隠しファイルを削除します。

これが将来誰か他の人に役立つことを願っています

#include <stdio.h>
#include <dirent.h>
#include <sys/stat.h>
#define SUCCESS_STAT 0

/**
 * checks if a specific directory exists
 * @param dir_path the path to check
 * @return if the path exists
 */
bool dirExists(std::string dir_path)
{
    struct stat sb;

    if (stat(dir_path.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode))
        return true;
    else
        return false;
}

/**
 * deletes all the files in a folder (but not the folder itself). optionally
 * this can traverse subfolders and delete all contents when recursive is true
 * @param dirpath the directory to delete the contents of (can be full or
 * relative path)
 * @param recursive true = delete all files/folders in all subfolders
 *                  false = delete only files in toplevel dir
 * @return SUCCESS_STAT on success
 *         errno on failure, values can be from unlink or rmdir
 * @note this does NOT delete the named directory, only its contents
 */
int DeleteFilesInDirectory(std::string dirpath, bool recursive)
{
    if (dirpath.empty())
        return SUCCESS_STAT;

    DIR *theFolder = opendir(dirpath.c_str());
    struct dirent *next_file;
    char filepath[1024];
    int ret_val;

    if (theFolder == NULL)
        return errno;

    while ( (next_file = readdir(theFolder)) != NULL )
    {
        // build the path for each file in the folder
        sprintf(filepath, "%s/%s", dirpath.c_str(), next_file->d_name);

        //we don't want to process the pointer to "this" or "parent" directory
        if ((strcmp(next_file->d_name,"..") == 0) ||
            (strcmp(next_file->d_name,"." ) == 0) )
        {
            continue;
        }

        //dirExists will check if the "filepath" is a directory
        if (dirExists(filepath))
        {
            if (!recursive)
                //if we aren't recursively deleting in subfolders, skip this dir
                 continue;

            ret_val = DeleteFilesInDirectory(filepath, recursive);

            if (ret_val != SUCCESS_STAT)
            {
                closedir(theFolder);
                return ret_val;
            }
        }

        ret_val = remove(filepath);
        //ENOENT occurs when i folder is empty, or is a dangling link, in
        //which case we will say it was a success because the file is gone
        if (ret_val != SUCCESS_STAT && ret_val != ENOENT)
        {
            closedir(theFolder);
            return ret_val;
        }

    }

    closedir(theFolder);

    return SUCCESS_STAT;
}
于 2016-08-05T18:30:26.767 に答える
0

nftw(3)を使用できます。まず、パスを作成して、削除するファイルパスのセットを収集します。次に、2番目のパスで(unlink非ディレクトリの場合)およびrmdir(2)を使用します

于 2016-08-05T18:38:47.090 に答える
0

C ++ 17以降では、 std::filesystemを使用できます。以下のコードは、directory_iteratorを使用してディレクトリ内のすべてのファイルとサブディレクトリを一覧表示し、remove_allを呼び出しそれらを削除します。

#include <filesystem>

namespace fs = std::filesystem;

void delete_dir_content(const fs::path& dir_path) {
    for (auto& path: fs::directory_iterator(dir_path)) {
        fs::remove_all(path);
    }
}

filesystem_errorこれにより、基になるOSAPIエラーで例外がスローされることに注意してください。これは次の方法で回避できます。

void delete_dir_content(const fs::path& dir_path) {
    for (auto& path: fs::directory_iterator(dir_path)) {
        std::error_code err;
        std::uintmax_t n = fs::remove_all(path, err);
        if (static_cast<std::uintmax_t>(-1) == n) {
            std::cout << "Failed to remove_all(" << path << ") with error: " << err.message() << std::endl;
        }
    }
}
于 2020-08-21T01:01:35.850 に答える