Skip to content

Instantly share code, notes, and snippets.

@yetimdasturchi
Last active December 7, 2022 23:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yetimdasturchi/e173faa252b765852eaa6460a27d43cf to your computer and use it in GitHub Desktop.
Save yetimdasturchi/e173faa252b765852eaa6460a27d43cf to your computer and use it in GitHub Desktop.
rm alternativ

Katta oqimdagi fayllarni tezkor o'chirish dasturi

Unix asosida ishlovchi rm va find -delete funksiyalari kattaroq hajmdagi fayllar sonida muammo chiqarishi ko'pchilik amaliyotida kuzatilgan. Yuqoridagi C kod aynan shu muammoni bartaraf etish va tmp fayllarni kerakli papkalardan tozalash uchun qo'l keladi

Kompiliyatsiya qilish:

gcc -std=c99 -g remover.c -o remover

Test uchun feyk fayllarni generatsiya qilish:

bash fake.sh

Faylni ishga tushirish:

./remover /tmp/fake

Natija

#!/bin/bash
for (( i=0; i <= 1000; ++i ))
do
tmpfile=$(mktemp /tmp/fake/abc-script.XXXXXXXXXXXXXXXXXXXXXXXXXX)
dd if=/dev/urandom of=$tmpfile bs=1M count=$(expr 1 + $RANDOM % 3)
done
#define _DEFAULT_SOURCE
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <unistd.h>
char *concat(const char *a, const char *b) {
int lena = strlen(a);
int lenb = strlen(b);
char *con = malloc(lena+lenb+1);
memcpy(con,a,lena);
memcpy(con+lena,b,lenb+1);
return con;
}
int remove_dir_contents(char* path, bool selfd){
DIR *d;
struct dirent *dir;
d = opendir( path );
int x = 0;
if ( d ) {
while ( ( dir = readdir( d ) ) != NULL) {
if ( dir->d_name[0] == '.' || dir->d_type == DT_CHR ) {
continue;
}else {
char* fullpath = concat("/", dir->d_name);
fullpath = concat(path, fullpath);
if ( dir->d_type == DT_DIR ) {
x = x + remove_dir_contents( fullpath, true );
if ( rmdir( fullpath ) != 0){
printf( "Papkani o'chirishda xatolik: %s\n", fullpath );
}else{
x++;
}
}else{
if ( unlink( fullpath ) != 0){
printf( "Faylni o'chirishda xatolik: %s\n", fullpath );
}else{
x++;
}
}
free(fullpath);
}
}
closedir(d);
}
return x;
}
int main(const int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Papka kiritilmadi!\n");
return -1;
}
int all_files = remove_dir_contents( argv[1], false );
printf("O'chirilgan fayllar: %d\n", all_files);
return(0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment