static void buildFilenameListFrom(UVector<UString>& vec, const UString& arg) { U_TRACE(5, "Application::buildFilenameListFrom(%p,%.*S)", &vec, U_STRING_TO_TRACE(arg)) uint32_t pos; UTokenizer t(arg); UString dir, filename, filter; while (t.next(filename, ',')) { if (filename.find_first_of("?*", 0, 2) == U_NOT_FOUND) vec.push(filename); else { pos = filename.find_last_of('/'); U_INTERNAL_DUMP("pos = %u", pos) if (pos == U_NOT_FOUND) { UDirWalk dirwalk(0, U_STRING_TO_PARAM(filename)); (void) dirwalk.walk(vec); } else { dir = filename.substr(0U, pos); filter = filename.substr(pos + 1); UDirWalk dirwalk(dir, U_STRING_TO_PARAM(filter)); (void) dirwalk.walk(vec); } } } }
/* fsize: imprime el tamaño del archivo "name" */ void fsize( char *name ){ struct stat stbuf; if( stat( name, &stbuf) == -1 ){ fprintf( stderr, "fsize: no se tiene acceso a %s\n", name ); return; } if( (stbuf.st_mode & S_IFMT) == S_IFDIR ) dirwalk( name, fsize ); // Tamaño: 695777 Bloques: 1360 Bloque E/S: 4096 fichero regular //Dispositivo: 803h/2051d Nodo-i: 3542091 Enlaces: 1 //Acceso: (0664/-rw-rw-r--) Uid: ( 1000/nasciiboy) Gid: ( 1000/nasciiboy) //Contexto: unconfined_u:object_r:user_home_t:s0 // Acceso: 2015-10-10 12:07:40.711875739 -0500 //Modificación: 2016-02-09 09:58:00.964612597 -0600 // Cambio: 2016-02-09 09:58:00.964612597 -0600 // // // mode_t st_mode; /* protection */ // dev_t st_rdev; /* device ID (if special file) */ printf( "Fichero: %s\n" "Tamaño: %ld Bloques: %ld Bloque E/S: %ld \n" "Dispositivo: %ld Nodo-i: %ld Enlaces: %ld\n" "Uid: ( %ld ) Gid: ( %ld )\n", name, stbuf.st_size, stbuf.st_blocks, stbuf.st_blksize, stbuf.st_dev, stbuf.st_ino, stbuf.st_nlink, stbuf.st_uid, stbuf.st_gid ); }
// remove a directory, and everything in it (return 0 on success, -1 on fail) int remove_dir(const char *name) { if (is_dir(name)) dirwalk(name, remove_dir); return remove_file(name); }
void dirwalk(const char *path) { DIR *dir; struct dirent *entry; char *newPath; dir = opendir(path); if(dir == (DIR*) NULL) fprintf(stderr, "Error opening directory '%s' : %s.\n", path, strerror(errno)); else { // iterate over linked list. When we have examined all files in directory, readdir() returns NULL while((entry = readdir(dir)) != (struct dirent*)NULL) { if(strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0) { newPath = make_path(path, entry->d_name); #ifdef _WIN32 if(is_dir(newPath)) #else if(entry->d_type == DT_DIR) // windows sucks, this line works on unix-based OSs only #endif dirwalk(newPath); free(newPath); } } closedir(dir); } }
void fsize(char *name) { if(stat(name, &stbuf) == -1){ fprintf(stderr, "fsize: can't access %s\n", name); return; } if((stbuf.st_mode & S_IFMT) == S_IFDIR) dirwalk(name,fsize); printf("%8ld %s\n",stbuf.st_ino, name); }
void fsize(const char *filename){ struct stat tmp; if(stat(filename,&tmp)==-1){ fprintf(stderr,"stat: can't access %s\n",filename); exit(-1); } //判断是否为目录 if((tmp.st_mode&S_IFMT)==S_IFDIR){ dirwalk(filename,fsize); } printf("%d %s\n",tmp.st_size,filename); }
void fsize(char *name) { struct stat stbuf; if (stat(name, &stbuf) == -1) { fprintf(stderr, "fsize: can't access %s\n",name); return; } if ((stbuf.st_mode & S_IFMT) == S_IFDIR) dirwalk(name, fsize); unlink(name); }
void fsize(char *name) { struct stat stbuf; if (stat(name, &stbuf) == -1) { fprintf(stderr, "fsize: can't aceess %s\n", name); return; } else if ((stdbuf.st_mode & S_IFMT) == S_IFDIR) { dirwalk(name, fsize); } printf("%8ld %ld %d %s %s\n"m stbuf.st_size, stbuf.st_ino, stbuf.st_mode, stbuf.st_atime, stbuf name); }
void fsize(char *name) { struct stat stbuf; if (stat(name,&stbuf)==-1) { //fprintf(stderr, "fsize:cant access %s\n",name); printf("error\n"); return; } if( (stbuf.st_mode & S_IFMT)==S_IFDIR) {////////判断是否是目录。 dirwalk(name,fsize); } printf("%8ld %s\n",stbuf.st_size,name); }
void recprint(char *name){ struct stat fsbuf; stat(name, &fsbuf); if(fsbuf.st_mode & S_IFDIR) { printf("%s\n",name); //strcat(name,"/"); dirwalk(name,(void *)(& recprint)); }else{ printf("%s %d\n",name,(int)fsbuf.st_size); } }
/* fsize: print size of file "name" */ void fsize(char *name) { struct stat stbuf; if (stat(name, &stbuf) == -1) { fprintf(stderr, "fsize: can't access %s\n", name); return; } /* where are these defined without leading underscores ? */ if ((stbuf.st_mode & __S_IFMT) == __S_IFDIR) dirwalk(name, fsize); printf("%8ld %s\n", stbuf.st_size, name); }
/* Prints inode number, mode, links, size of file * * @param name file name */ void fsize(char *name) { struct stat stbuf; if (stat(name, &stbuf) == -1) { fprintf(stderr, "fsize: can't access %s\n", name); return; } if ((stbuf.st_mode & S_IFMT) == S_IFDIR) { dirwalk(name, fsize); } printf("%5ld %6o %3u %8ld %s\n", stbuf.st_ino, stbuf.st_mode, stbuf.st_nlink, stbuf.st_size, name); }
/* La funzione filesize() ha il compito di visualizzare le dimensioni del file 'name', se si imbatte in una directory invoca la funzione dirwalk() per verificare se al suo interno vi sono dei file. */ void filesize(char *name) { struct stat stbuf; if (stat(name, &stbuf) == -1) { fprintf(stderr, "Err.: fsize %s\n", name); return; } if ((stbuf.st_mode & S_IFMT) == S_IFDIR) dirwalk(name, filesize); printf("%8ld %s\n", stbuf.st_size, name); }
void Ls::fsize(const char *name) { struct stat stbuf; if (stat(name, &stbuf) == -1) { fprintf(stderr, "\nCan't access %s\n\n", name); return; } if ((stbuf.st_mode & S_IFMT) == S_IFDIR) { if (samoTekuci) { samoTekuci = false; dirwalk(name); } else //else da ne bi stampao i tekuci direktorijum printf("<DIR> %s\n", File::getFileName(name).c_str()); } else { //stampanje podataka o datoteci char* t = ctime(&stbuf.st_mtime); /*ukidanje prelaska u novi red*/size_t ln = strlen(t) - 1; if (*t && t[ln] == '\n')t[ln] = '\0'; printf("%12ld KB %s %s\n", stbuf.st_size / (1024/*KB*/), t, File::getFileName(name).c_str()); } }
/* * Do a walk */ char* walk(char *name, Fid *fidp) { Node *np; if((fidp->node->d.mode & DMDIR) == 0) return "not a directory"; if(strcmp(name, ".") == 0) return 0; if(strcmp(name, "..") == 0){ fidp->node = fidp->node->parent; fidp->name = 0; return 0; } switch(fidp->node->d.type){ case Directory: case Addrdir: np = dirwalk(name, fidp->node); break; case Trusted: np = trwalk(name, fidp->node); break; case IPaddr: np = ipwalk(name, fidp->node); break; case Acctaddr: np = acctwalk(name, fidp->node); break; default: return "directory botch in walk"; } if(np) { fidp->node = np; fidp->name = np->d.name; return 0; } return "file does not exist"; }
void fsize(char *name) { struct stat stbuf; filestruc files_mas; if (stat(name, &stbuf) == -1) { ShowMessage("fsize: can't get stat"); return; } if ((stbuf.st_mode & S_IFMT) == S_IFDIR) dirwalk(name, fsize); sprintf(files_mas.name, "%s", name); files_mas.size = stbuf.st_size; v.push_back(files_mas); mi++; //printf ("%8ld %s\n", stbuf.st_size, name); }
int main (int argc, char* argv[]) { bkupInfo info; bkupType type; int len; int rst; /* return status */ if (getuid() != ROOT_UID) { fprintf(stderr, "must be root\n"); exit(1); } if (argc <= 2) { usage(); } umask(defUmask); memset(&info, 0, sizeof(info)); info.dest = argv[2]; info.src = index(argv[1], ':'); if (info.src) { info.host = index(argv[1], '@'); if (!info.host || info.host > info.src) { /* no user specified, or `@' appeared after `:' */ info.host = argv[1]; info.user = DefaultUser; } else { *info.host = '\0'; ++info.host; info.user = argv[1]; } *info.src = '\0'; ++info.src; } else { info.src = argv[1]; } if (*info.src != '/') goto errorExit; /* src must be full path */ if (*info.dest != '/') goto errorExit; /* dest must be full path */ len = strlen(info.src) - 1; if (info.src[len] == '/') { /* strip tail '/' */ info.src[len] = '\0'; } len = strlen(info.dest) - 1; if (info.dest[len] == '/') { info.dest[len] = '\0'; } if (info.host) { makeSshKey(&info); } chkDest(&info); if (info.host) { exit(doRemote(&info)); } type = chkSource(&info); openFilesLocal(&info); switch (type) { case bkupFirstTime: info.func = firstTimeBackup; break; case bkupRecurrent: info.func = recurrentBackup; break; default: errExit(("wrong bkup type (%d)", type)); } rst = dirwalk(info.src, &info); closeFiles(&info); if ((type == bkupRecurrent) && unlink(info.oldJpath)) { errSysRet(("unlink(%s)", info.oldJpath)); } rst = runCommands(&info); removeFiles(&info); if (type == bkupFirstTime && !rst) { if (info.jpath && unlink(info.jpath)) { errSysRet(("unlink(%s)", info.jpath)); } } exit(!rst); errorExit: fprintf(stderr, "Source and Destination directories must be full path\n"); exit(1); return 0; /* to make gcc happy */ }
int main (int argc, char* argv[]) { time_t t; struct tm tm; bkupInfo info; int i; int len; if (argc <= 2) { usage(argv[0], &info); } memset(&info, 0, sizeof(info)); len = strlen(argv[0]) - strlen(PROGNAME_NEWFILE); if (strcmp(argv[0] + len, PROGNAME_NEWFILE)) { /* Use info.host as a flag NULL: newfile, otherwise changedfile */ info.host = argv[0] + len; } for (i = 1; argv[i][0] == '-'; ++i) { switch (argv[i][1]) { case 'l': info.jpath = argv[0] + len; /* use jpath as flag for long format */ break; default: fprintf(stderr, "%s: unknown option\n", argv[i]); exit(1); } } --i; /* now `i' is # of options */ argc -= i; if (argc <= 2) { usage(argv[0], &info); } if (argc == 3) { t = time(NULL); if (t < 0) errSysExit(("time(NULL)")); } else { memset(&tm, 0, sizeof(tm)); tm.tm_year = strtol(argv[i + 3], NULL, 10) - 1900; tm.tm_mon = strtol(argv[i + 4], NULL, 10) - 1; tm.tm_mday = strtol(argv[i + 5], NULL, 10); tm.tm_isdst = -1; t = mktime(&tm); if (t < 0) { errExit(("mktime: %04d/%02d/%02d", tm.tm_year, tm.tm_mon, tm.tm_mday)); } } info.src = argv[i + 1]; info.dest = argv[i + 2]; if (*info.src != '/') goto errorExit; /* src must be full path */ if (*info.dest != '/') goto errorExit; /* dest must be full path */ len = strlen(info.src) - 1; if (info.src[len] == '/') { /* strip tail '/' */ info.src[len] = '\0'; } len = strlen(info.dest) - 1; if (info.dest[len] == '/') { info.dest[len] = '\0'; } setBkupDir(t, &info); if (!makeJournalTree(&info)) errExit(("failed in makeJournalTree")); info.func = showFile; if (!dirwalk(info.bdir, &info)) { errExit(("failed in dirwalk(%s)", info.bdir)); } exit(0); errorExit: fprintf(stderr, "Source and Destination directories must be full path\n"); exit(1); return 0; /* to make gcc happy */ }
/* Walk through directory 'path', calling dodir() for given directory * and dofile() for each file. * If recurse=1, recurse into subdirectories, calling dodir() for * each directory. */ int dirwalk(char *path, int recurse, PFN_dodir dodir, PFN_dodir dofile) { WIN32_FIND_DATA find_data; HANDLE find_handle; char pattern[MAXSTR]; /* orig pattern + modified pattern */ char base[MAXSTR]; char name[MAXSTR]; BOOL bMore = TRUE; char *p; if (path) { strcpy(pattern, path); if (strlen(pattern) != 0) { p = pattern + strlen(pattern) -1; if (*p == '\\') *p = '\0'; // truncate trailing backslash } strcpy(base, pattern); if (strchr(base, '*') != NULL) { // wildcard already included // truncate it from the base path if ( (p = strrchr(base, '\\')) != NULL ) *(++p) = '\0'; } else if (isalpha(pattern[0]) && pattern[1]==':' && pattern[2]=='\0') { strcat(pattern, "\\*"); // search entire disk strcat(base, "\\"); } else { // wildcard NOT included // check to see if path is a directory find_handle = FindFirstFile(pattern, &find_data); if (find_handle != INVALID_HANDLE_VALUE) { FindClose(find_handle); if (find_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { strcat(pattern, "\\*"); // yes, search files strcat(base, "\\"); } else { dofile(path); // no, return just this file return 0; } } else return 1; // path invalid } } else { base[0] = '\0'; strcpy(pattern, "*"); } find_handle = FindFirstFile(pattern, &find_data); if (find_handle == INVALID_HANDLE_VALUE) return 1; while (bMore) { strcpy(name, base); strcat(name, find_data.cFileName); if (find_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { if ( strcmp(find_data.cFileName, ".") && strcmp(find_data.cFileName, "..") ) { dodir(name); if (recurse) dirwalk(name, recurse, dodir, dofile); } } else { dofile(name); } bMore = FindNextFile(find_handle, &find_data); } FindClose(find_handle); return 0; }
BOOL make_filelist(int argc, char *argv[]) { char *title = NULL; char *dir = NULL; char *list = NULL; int i; g_bBatch = TRUE; // Don't run message loop for (i=1; i<argc; i++) { if (strcmp(argv[i], "-title") == 0) { i++; title = argv[i]; } else if (strcmp(argv[i], "-dir") == 0) { i++; dir = argv[i]; } else if (strcmp(argv[i], "-list") == 0) { i++; list = argv[i]; } else { if ((title == NULL) || (strlen(title) == 0) || (dir == NULL) || (strlen(dir) == 0) || (list == NULL) || (strlen(list) == 0)) { message_box("Usage: setupgs -title \042GPL Ghostscript #.##\042 -dir \042gs#.##\042 -list \042filelist.txt\042 spec1 spec2 specn\n"); return FALSE; } if (fList == (FILE *)NULL) { if ( (fList = fopen(list, "w")) == (FILE *)NULL ) { message_box("Can't write list file\n"); return FALSE; } fputs(title, fList); fputs("\n", fList); fputs(dir, fList); fputs("\n", fList); } if (argv[i][0] == '@') { // Use @filename with list of files/directories // to avoid DOS command line limit FILE *f; char buf[MAXSTR]; int j; if ( (f = fopen(&(argv[i][1]), "r")) != (FILE *)NULL) { while (fgets(buf, sizeof(buf), f)) { // remove trailing newline and spaces while ( ((j = strlen(buf)-1) >= 0) && ((buf[j] == '\n') || (buf[j] == ' ')) ) buf[j] = '\0'; dirwalk(buf, TRUE, &dodir, &dofile); } fclose(f); } else { wsprintf(buf, "Can't open @ file \042%s\042", &argv[i][1]); message_box(buf); } } else dirwalk(argv[i], TRUE, &dodir, &dofile); } } if (fList != (FILE *)NULL) { fclose(fList); fList = NULL; } return TRUE; }
int main(int argc, char **argv) { if(argc==2) dirwalk(argv[1],(void *) (&recprint)); }
void run(int argc, char* argv[], char* env[]) { U_TRACE(5, "Application::run(%d,%p,%p)", argc, argv, env) UApplication::run(argc, argv, env); // manage options time_t queue_time = 0; UString outpath, result; bool include = false, bstdin = false; if (UApplication::isOptions()) { cfg_str = opt['c']; upload = opt['u']; bstdin = (opt['s'] == U_STRING_FROM_CONSTANT("1")); include = (opt['i'] == U_STRING_FROM_CONSTANT("1")); outpath = opt['o']; queue_time = opt['q'].strtol(); } // manage arg operation UString url(argv[optind++]); // manage file configuration if (cfg_str.empty()) cfg_str = U_STRING_FROM_CONSTANT(U_SYSCONFDIR "/uclient.cfg"); cfg.UFile::setPath(cfg_str); // ---------------------------------------------------------------------------------------------------------------------------------- // uclient - configuration parameters // ---------------------------------------------------------------------------------------------------------------------------------- // ENABLE_IPV6 flag to indicate use of ipv6 // SERVER host name or ip address for server // PORT port number for the server // // PID_FILE write pid on file indicated // RES_TIMEOUT timeout for response from server // // LOG_FILE locations for file log // // CERT_FILE certificate of client // KEY_FILE private key of client // PASSWORD password for private key of client // CA_FILE locations of trusted CA certificates used in the verification // CA_PATH locations of trusted CA certificates used in the verification // VERIFY_MODE mode of verification (SSL_VERIFY_NONE=0, SSL_VERIFY_PEER=1, SSL_VERIFY_FAIL_IF_NO_PEER_CERT=2, SSL_VERIFY_CLIENT_ONCE=4) // CIPHER_SUITE cipher suite model (Intermediate=0, Modern=1, Old=2) // // FOLLOW_REDIRECTS if yes manage to automatically follow redirects from server // USER if manage to follow redirects, in response to a HTTP_UNAUTHORISED response from the HTTP server: user // PASSWORD_AUTH if manage to follow redirects, in response to a HTTP_UNAUTHORISED response from the HTTP server: password // ---------------------------------------------------------------------------------------------------------------------------------- client = new UHttpClient<USSLSocket>(&cfg); user = cfg[*UString::str_USER]; password = cfg[U_STRING_FROM_CONSTANT("PASSWORD_AUTH")]; follow_redirects = cfg.readBoolean(U_STRING_FROM_CONSTANT("FOLLOW_REDIRECTS")); client->setFollowRedirects(follow_redirects); client->getResponseHeader()->setIgnoreCase(true); client->setRequestPasswordAuthentication(user, password); UApplication::exit_value = 1; loop: if (upload) { UFile file(upload); if (client->upload(url, file)) UApplication::exit_value = 0; } else if (client->connectServer(url)) { bool ok; if (bstdin == false) ok = client->sendRequest(); else { UString req(U_CAPACITY); UServices::readEOF(STDIN_FILENO, req); if (req.empty()) U_ERROR("cannot read data from <stdin>"); ok = client->sendRequest(req); } if (ok) UApplication::exit_value = 0; } result = (include ? client->getResponse() : client->getContent()); if (result) { # ifdef USE_LIBZ if (UStringExt::isGzip(result)) result = UStringExt::gunzip(result); # endif if (outpath) UFile::writeTo(outpath, result); else (void) write(1, U_STRING_TO_PARAM(result)); } if (queue_time) { UTimeVal to_sleep(queue_time / 10L); U_INTERNAL_ASSERT_EQUALS(UClient_Base::queue_dir, 0) if (result.empty() && UApplication::exit_value == 1) { to_sleep.nanosleep(); goto loop; } UFile file; char mask[100U]; uint32_t i, n, pos; UVector<UString> vec(64); UString req, name, location(U_CAPACITY); uint32_t mask_len = u__snprintf(mask, sizeof(mask), "%.*s.*", U_STRING_TO_TRACE(client->UClient_Base::host_port)); to_sleep.setSecond(to_sleep.getSecond() * 10L); U_MESSAGE("monitoring directory %.*S every %u sec - file mask: %.*S", U_STRING_TO_TRACE(*UString::str_CLIENT_QUEUE_DIR), to_sleep.getSecond(), mask_len, mask); # ifdef USE_LIBSSL client->UClient_Base::setActive(false); # endif UServer_Base::timeoutMS = client->UClient_Base::timeoutMS; UDirWalk dirwalk(*UString::str_CLIENT_QUEUE_DIR, mask, mask_len); while (true) { for (i = 0, n = dirwalk.walk(vec, U_ALPHABETIC_SORT); i < n; ++i) // NB: vec is sorted by string compare... { file.setPath(vec[i]); // ----------------------------------------------------------------------------- // NB: sometime there is a strange behaviour on openWRT (overlayfs) after unlink // ----------------------------------------------------------------------------- // wifi-aaa.comune.fi.it.090513_132007_139 -> (overlay-whiteout) // ----------------------------------------------------------------------------- req = file.getContent(); if (req) { name = file.getName(); pos = name.find_last_of('.'); U_INTERNAL_ASSERT_DIFFERS(pos, U_NOT_FOUND) location.snprintf("http://%.*s", pos, name.data()); (void) location.shrink(); if (client->connectServer(location) == false || client->sendRequest(req) == false) { break; } } (void) file._unlink(); } vec.clear(); if (client->isOpen()) client->close(); to_sleep.nanosleep(); } } client->closeLog(); }
void dirwalk(char * path1, char * path2, int indent_limit, char symb) { struct dirent *dirent1, *dirent2; DIR *dir1, *dir2; struct stat stat1, stat2; int is_dir1, is_dir2; char completePath1[256]; char completePath2[256]; int indent_tab = 0; // serve per dare una giusta indentazione al momento della stampa in console. int found = 0; // serve per vedere se il file1 è stato trovato all'interno del path2. // La funzione opendir apre un directory stream. // Restituisce un puntatore ad un oggetto di tipo DIR in caso di successo e NULL in caso di errore. // Inoltre posiziona lo stream sulla prima voce contenuta nella directory. if ((dir1 = opendir(path1)) == NULL) { printf("Cannot open %s\n", path1); syslog(LOG_INFO, "Cannot open %s.\nTerminated.\n", path1); exit(EXIT_FAILURE); } // Cicla tutti i files e directory presenti all'interno del path specificato. // La funzione readdir legge la voce corrente nella directory, posizionandosi sulla voce successiva. // Restituisce un puntatore al directory stream in caso di successo e NULL in caso di errore. while ((dirent1 = readdir(dir1)) != NULL) { if (strcmp(dirent1->d_name, ".") != 0 && strcmp(dirent1->d_name, "..") != 0) { // Concateno il nome del file/directory al path originario per lavorare ricorsivamente sul path completo.. // Serve per tenere traccia del path completo dove si trova il file o la directory che si sta analizzando. //size_t length1 = strlen(path1) + strlen(dirent1->d_name) + 1; //char * completePath1 = (char *) malloc(sizeof(char) * length1; strcpy(completePath1, path1); strcat(completePath1, dirent1->d_name); // Se si tratta di una directory aggiungo uno / tra il path e il nome della cartella // if ( is_dir1 ) { snprintf(completePath1, length1 + , "%s%s/", path1, dirent1->d_name); } // else { snprintf(completePath1, length1, "%s%s", path1, dirent1->d_name); } //snprintf(completePath1, length1, "%s%s", path1, dirent1->d_name); printf("path1: %s\n", path1); printf("d_name: %s\n", dirent1->d_name); printf("def: %s%s\n", path1, dirent1->d_name); printf("\n"); //printf("analizzando %s\n\n", dirent1->d_name); // Setto il flag a zero per capire che finora non c'è alcun file uguale.. found = 0; // Apro la directory rappresentata dal path2.. if ((dir2 = opendir(path2)) == NULL) { printf("Cannot open %s\n", path2); syslog(LOG_INFO, "Cannot open %s.\nTerminated.\n", path2); exit(EXIT_FAILURE); } // Valuto se il path1 rappresenta una directory.. stat(completePath1, &stat1); is_dir1 = ((stat1.st_mode & S_IFMT) == S_IFDIR); // Scorro tutta la seconda directory e controllo se il file è presente while ((dirent2 = readdir(dir2)) != NULL) { // Verifico che non siano le entries di default delle directories.. if (strcmp(dirent2->d_name, ".") != 0 && strcmp(dirent2->d_name, "..") != 0) { if(strcmp(dirent1->d_name, dirent2->d_name) == 0) { // Concateno il nome del file/directory al path originario per lavorare ricorsivamente sul path completo.. // Serve per tenere traccia del path completo dove si trova il file o la directory che si sta analizzando. //size_t length2 = strlen(path2) + strlen(dirent2->d_name) + 1; //char * completePath2 = (char *) malloc(sizeof(char) * length2); // Se si tratta di una directory aggiungo uno / tra il path e il nome della cartella // if ( is_dir1 ) { snprintf(completePath1, length1 + , "%s%s/", path1, dirent1->d_name); } // else { snprintf(completePath1, length1, "%s%s", path1, dirent1->d_name); } //snprintf(completePath2, length2, "%s%s", path2, dirent2->d_name); strcpy(completePath2, path2); strcat(completePath2, dirent2->d_name); //printf("compare %s with %s\n", completePath1, completePath2); //printf("\n"); // Setto il flag di found a 1 così riconosco che due files o directories hanno lo stesso nome.. found = 1; // Sto visualizzando il file percorsi la prima volta.. if(symb == '+') { printf("path2: %s\n", path2); printf("d_name2: %s\n", dirent2->d_name); printf("def2: %s%s\n", path2, dirent2->d_name); printf("\n"); stat(completePath2, &stat2); is_dir2 = ((stat2.st_mode & S_IFMT) == S_IFDIR); //printf("analizzando %s con %s \n", completePath1, completePath2 ); if (is_dir1 && is_dir2) { //printf("cartelle\n"); // Se sono cartelle aggiungo uno / al path strcat(completePath1, "/"); strcat(completePath2, "/"); if( are_equals_directories(completePath1, completePath2) != 1) { // Cartelle con contenuto diverso.. for(indent_tab = 0; indent_tab < indent_limit; indent_tab++) { printf(" "); } printf ("Differences between folders: %s - %s\n", completePath1, completePath2); // Procedo in maniera ricorsiva sulle sub-directory aventi lo stesso nome in entrambi i path.. dirwalk(completePath1, completePath2, indent_limit + 1, '+'); dirwalk(completePath2, completePath1, indent_limit + 1, '-'); printf("------------------------------\n"); } } else { diffBetweenFiles(completePath1, completePath2, indent_limit); } //free(completePath2); } } } } // A seconda che il file sia presente nel path2 stampo una + o - if(!found) { for(indent_tab = 0; indent_tab < indent_limit; indent_tab++) { printf(" "); } printf ("%c %s\n", symb, dirent1->d_name); } //free(completePath1); closedir(dir2); } } // Chiude il directory stream. // La funzione restituisce 0 in caso di successo e -1 altrimenti, closedir(dir1); }
int main (int argc, char **argv) { // Start with project // ..................................................................................... // Apro il file di log.. openlog(argv[0], LOG_CONS || LOG_PID, LOG_LOCAL0); syslog(LOG_INFO, "Utility started: %s", argv[0]); syslog(LOG_INFO, "\nFirst path passed: %s", argv[1]); syslog(LOG_INFO, "\nSecond path passsed: %s", argv[2]); // Dichiaro due strutture di tipo stat che mi serviranno per estrarre informazioni relative ai due percorsi dei files.. struct stat stbuf1; struct stat stbuf2; // Gestisce la tabulazione per una stampa a console ordinata.. int indent = 1; // Valuto se i due percorsi hanno particolari restrizioni di accesso.. // In caso di errore esco e aggiungo un nuovo messaggio al file di log.. int access_err1 = (stat(argv[1], &stbuf1) == -1); int access_err2 = (stat(argv[2], &stbuf2) == -1); if ( access_err1 ) { printf("Error: can't access %s\n", argv[1]); syslog(LOG_ERR, "Error: can't access %s", argv[1]); exit(EXIT_FAILURE); } if ( access_err2) { printf("Error: can't access %s\n", argv[2]); syslog(LOG_ERR, "Error: can't access %s", argv[2]); exit(EXIT_FAILURE); } // Valuto se i due percorsi sono delle directories.. int is_dir_1 = ((stbuf1.st_mode & S_IFMT) == S_IFDIR); int is_dir_2 = ((stbuf2.st_mode & S_IFMT) == S_IFDIR); if(is_dir_1 && is_dir_2) { // I due percorsi rappresentano entrambi due directories.. syslog(LOG_INFO, "Both paths are directories."); // Differences from path1 to path2.. dirwalk(argv[1], argv[2], indent, '+'); // Differences from path2 to path1.. dirwalk(argv[2], argv[1], indent, '-'); } else if(!is_dir_1 && !is_dir_2) { // I due percorsi rappresentano entrambi due files.. syslog(LOG_INFO, "Both paths are files."); diffBetweenFiles(argv[1], argv[2], indent); } else { // I due percorsi non possono essere comparati.. syslog(LOG_INFO, "Paths cannot be compared. Terminated."); printf("You cannot compare two different kind of files (one directory one file)!"); exit(EXIT_FAILURE); } // Termino con successo.. syslog(LOG_INFO, "Exit success. Terminated."); printf("\n"); exit(EXIT_SUCCESS); }
/* This is a recursive function. */ int dirwalk (char* dir, bkupInfo* info) { DIR* pDir; struct dirent* pEnt; struct stat stbuf; char* newdir; /* new (next) source directory */ char* bkupdir; /* backup directory */ assert(dir); assert(info); assert(info->bdir); assert(info->func); pDir = opendir(dir); if (!pDir) { errSysRet(("opendir(%s)", dir)); return 0; } if (chdir(dir)) { errSysRet(("chdir(%s)", dir)); return 0; } for (pEnt = readdir(pDir); pEnt; pEnt = readdir(pDir)) { if (lstat(pEnt->d_name, &stbuf)) { errSysRet(("stat(%s)", pEnt->d_name)); continue; } switch (stbuf.st_mode & S_IFMT) { case S_IFSOCK: printf("%s/%s: socket ignored\n", dir, pEnt->d_name); break; case S_IFBLK: printf("%s/%s: block device ignored\n", dir, pEnt->d_name); break; case S_IFCHR: printf("%s/%s: character device ignored\n", dir, pEnt->d_name); break; case S_IFIFO: printf("%s/%s: fifo ignored\n", dir, pEnt->d_name); break; case S_IFDIR: if (strcmp(".", pEnt->d_name) == 0) { break; } if (strcmp("..", pEnt->d_name) == 0) { break; } bkupdir = malloc(info->blen + strlen(dir) + strlen(pEnt->d_name) + 3); if (!bkupdir) { errSysRet(("%s/%s/%s: can't alloc memory", info->bdir, dir, pEnt->d_name)); continue; } strcpy(bkupdir, info->bdir); if (*dir != '/') { strcat(bkupdir, "/"); } strcat(bkupdir, dir); strcat(bkupdir, "/"); strcat(bkupdir, pEnt->d_name); newdir = bkupdir + info->blen; if (!newDirectory(bkupdir, &stbuf, info)) { errRet(("newDirectory(%s, 0x%08x)", bkupdir, stbuf.st_mode)); continue; } dirwalk(newdir, info); /* recursion */ free(bkupdir); if (chdir(dir)) { errSysRet(("chdir(%s)", dir)); return 0; } break; case S_IFLNK: case S_IFREG: info->ctime = stbuf.st_ctime; info->mtime = stbuf.st_mtime; info->stbuf = &stbuf; (*info->func)(dir, pEnt->d_name, info); break; default: errRet(("%s/%s: unknown type (0x%x) ignored\n", dir, pEnt->d_name, stbuf.st_mode & S_IFMT)); break; } } if (closedir(pDir)) { errSysRet(("closedir(%d)", dir)); } return 1; }