uso una todos suprimir sitio quitar que puede poder para office los esta escritorio eliminarla eliminar elementos deja debe como carpeta bibliotecas biblioteca archivo c++ c linux unix

c++ - una - eliminar bibliotecas windows 10



¿Cómo eliminar todos los archivos de una carpeta, pero no eliminar la carpeta utilizando las bibliotecas estándar de NIX? (7)

Estoy tratando de crear un programa que elimine el contenido de la carpeta / tmp, estoy usando C / C ++ en Linux.

system("exec rm -r /tmp")

borra todo lo que hay en la carpeta pero también borra la carpeta que no quiero.

¿Hay alguna forma de hacerlo mediante algún tipo de script bash, llamado via system() ; ¿O hay una manera directa de hacer esto en C / C ++?

Mi pregunta es similar a esta, pero no estoy en OS X ... ¿cómo eliminar todos los archivos de una carpeta, pero no la carpeta en sí?


Al utilizar el carácter comodín * , puede eliminar todos los archivos con cualquier tipo de extensión.

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


En C / C ++ puede usar (incluyendo directorios ocultos):

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

Pero, ¿qué pasa si las utilidades ''rm'' o ''find'' no están disponibles para sh?, Mejor vaya ''ftw'' y ''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; }


En C / C ++, podrías hacer:

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

En Bash, podrías hacer:

rm -r /tmp/*

Esto eliminará todo dentro de / tmp, pero no / tmp en sí.


Me doy cuenta de que esta es una pregunta muy antigua, pero a partir de la gran respuesta de Demitri, creé una función que eliminará archivos de forma recursiva en subcarpetas si así lo desea.

También hace algún manejo de errores, ya que devuelve errno. El encabezado de la función está escrito para su análisis por doxygen. Esta función funciona en los casos de ejemplo simple que usé, y elimina las carpetas ocultas y los archivos ocultos.

Espero que esto ayude a alguien más en el futuro.

#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; }


Podrías usar nftw(3) . Primero, haga un pase para recopilar el conjunto de rutas de archivo para eliminar. Luego use unlink (para no directorios) y rmdir(2) en una segunda pasada


tu puedes hacer

system("exec find /tmp -mindepth 1 -exec rm {} '';''");


#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; }

No desea generar un nuevo shell a través del system() o algo por el estilo, eso implica una gran cantidad de gastos para hacer algo muy simple y hace suposiciones (y dependencias) innecesarias sobre lo que está disponible en el sistema.