Pagina 1 di 2 1 2 ultimoultimo
Visualizzazione dei risultati da 1 a 10 su 15
  1. #1

    [C] Scansione directory

    Devo fare la scansione di una directory in modo da avere l'elenco dei file contenuti in quella directory e nelle sottodirectory.

    ho trovato questo:
    codice:
    	struct dirent **namelist; 
    	int n; 
    	n = scandir(".", &namelist, 0, alphasort); 
    	if (n < 0) 
    		perror("scandir"); 
    	else 
    		while(n--) 
    			printf("%s\n", namelist[n]->d_name);
    Che mi fa la scansione della directory iin cui sto lavorando, ma a me ne serve scandirne un'altra

    o questo
    codice:
    	struct dirent *d;
     	DIR *dp;
      	//apertura della directory 
      	if ((dp=opendir(home)) == NULL)
    	{
    		exit (EXIT_FAILURE);
    	}
    	// stampa dei nomi dei file contenuti nella directory 
      	while (d = readdir(dp))
      	{
         		if (d->d_ino != 0)
    		{
            		printf("%s\n", d->d_name);
    		}
      	}
      	closedir(dp);
    in cui mi fa la scansione della dir giusta, ma non mi va nelle stottodirectory.

    Qualcuno sa darmi una mano?

  2. #2
    Ok, nel primo esempio in scandir se cambio la directory mi fa lo scan della home, ma non mi va nelle sottodirectory.

    Come faccio a fare una ricorsione?
    C'è una funzione isdir o qualcosa del genere?

  3. #3

  4. #4
    Utente di HTML.it L'avatar di andbin
    Registrato dal
    Jan 2006
    residenza
    Italy
    Messaggi
    18,254

    Re: [C] Scansione directory

    Originariamente inviato da bonzox
    in cui mi fa la scansione della dir giusta, ma non mi va nelle stottodirectory.
    La tua funzione dovrebbe:
    a) essere preferibilmente ricorsiva (si potrebbe anche fare non ricorsiva ma dovrebbe usare delle strutture dati specifiche).
    b) per ogni elemento ottenuto comporre il path completo e corretto (non so a priori dove hai la 'current directory') e poi chiamare la funzione stat() e determinare (grazie anche alla macro S_ISDIR) se il campo st_mode della struttura indica che è una directory.
    Andrea, andbin.devSenior Java developerSCJP 5 (91%) • SCWCD 5 (94%)
    Java Versions Cheat Sheet

  5. #5
    Eccoti un esempio:

    codice:
    #include <stdio.h>
    #include <io.h>
    #include <time.h>
    #include <stdlib.h>
    #include <string.h>
    #include <direct.h>
    
    
    #define ARRAY_SIZE(Array) \
       (sizeof(Array) / sizeof((Array)[0]))
    
    #define BOOL short
    #define TRUE 1
    #define FALSE 0
    
    
    /////////////////////////////////////////////////////////////
    
    typedef struct
    {
    	int				nDepth;
    	BOOL				fRecurse;
    	char				szBuf[1024];
    	int				nIndent;
    	BOOL				fOk;
    	BOOL				fIsDir;
    	struct _finddata_t	FindData;
    } DIRWALKDATA, *LPDIRWALKDATA;
    
    
    BOOL IsChildDir (struct _finddata_t *lpFindData)
    {
    	BOOL bRet = (lpFindData->attrib & _A_SUBDIR) &&
    				(lpFindData->name[0] != '.');
    	
    	return bRet;
    }
    
    BOOL FindNextChildDir (long hFindFile, struct _finddata_t *lpFindData)
    {
    	BOOL fFound = FALSE;
    
    	int nFind;
    
    	do
    	{
    		nFind = _findnext(hFindFile, lpFindData);
    		if ( nFind == 0 )
    			fFound = TRUE;
    		else
    			fFound = FALSE;
    	} while ( fFound && !IsChildDir(lpFindData) );
    	
    	return(fFound);
    }
    
    long FindFirstChildDir (char * szPath, struct _finddata_t *lpFindData)
    {
    	BOOL fFound;
    
    	long hFindFile = _findfirst(szPath, lpFindData);
    
    	if (hFindFile != -1L)
    	{
    		fFound = IsChildDir(lpFindData);
    
    		if (!fFound)
    			fFound = FindNextChildDir(hFindFile, lpFindData);
    
    		if (!fFound)
    		{
    			_findclose(hFindFile);
    			hFindFile = -1L;
    		}
    	}
    	return(hFindFile);
    }
    
    void DirWalkRecurse (LPDIRWALKDATA pDW)
    {
    	long hFind;
    	pDW->nDepth++;
    	
    	pDW->nIndent = 3 * pDW->nDepth;
    	sprintf(pDW->szBuf, "%*s", pDW->nIndent, "");
    
    	_getcwd(&pDW->szBuf[pDW->nIndent],
    			ARRAY_SIZE(pDW->szBuf) - pDW->nIndent);
    
    	printf("pDW->szBuf -----> %s\n", pDW->szBuf);
    
    	hFind = _findfirst("*.*", &pDW->FindData);
    	pDW->fOk = ( hFind != -1L );
    
    	while (pDW->fOk)
    	{
    		pDW->fIsDir = pDW->FindData.attrib & _A_SUBDIR;
    
    		if (!pDW->fIsDir ||
    			(!pDW->fRecurse && IsChildDir(&pDW->FindData)))
    		{
    			sprintf(pDW->szBuf,
    					pDW->fIsDir ? "%*s[%s]" : "%*s%s",
    					pDW->nIndent, "",
    					pDW->FindData.name);
    
    			printf("pDW->szBuf -----> %s\n", pDW->szBuf);
    		}
    
    		pDW->fOk = _findnext(hFind, &pDW->FindData) == 0 ? TRUE : FALSE;
    	}
    	
    	if ( hFind != -1L )
    		_findclose(hFind);
    
    	if ( pDW->fRecurse )
    	{
    		hFind = FindFirstChildDir("*.*", &pDW->FindData);
    		pDW->fOk = (hFind != -1L);
    		
    		while ( pDW->fOk )
    		{
    			if ( _chdir(pDW->FindData.name) == 0 )
    			{
    				DirWalkRecurse(pDW);
    				_chdir("..");
    			}
    			pDW->fOk = FindNextChildDir(hFind, &pDW->FindData);
    		}
    		
    		if ( hFind != -1L )
    			_findclose(hFind);
    	}
    	
    	pDW->nDepth--;
    }
    
    void DirWalk (char * pszRootPath, BOOL fRecurse)
    { 
    	char szCurrDir[_MAX_DIR];
    	DIRWALKDATA DW;
    
    	_getcwd(szCurrDir, ARRAY_SIZE(szCurrDir));
    
    	_chdir(pszRootPath);
    
    	DW.nDepth = -1;
    
    	DW.fRecurse = fRecurse;
    
    	DirWalkRecurse(&DW);
    
    	_chdir(szCurrDir);
    }
    
    int main(int argc, char* argv[])
    {
    	DirWalk("c:\\Tear", TRUE);
    
    	return 0;
    }
    passando FALSE nel secondo parametro della funzione DirWalk, legge solo la directory passata nel primo parametro; con TRUE, invece, legge anche le sottodirectory.

  6. #6
    Grazie dell'esempio, me lo studio.

    Però ho visto C:\\

    e quindi specifico che a me serve su linux questa scansione.

    Grazie e appena ho studiato un po' mi faccio risentire

  7. #7
    Io il codice l'ho compilato col visual studio 6 per windows e funziona.

    Su linux dovresti sostituire le funzioni "_findfirst" e "_findnext" con (penso) "opendir" e "readdir"; la struttura _finddata_t dovrebbe corrispondere, invece, a "DIR".

    questo esempio forse potrà esserti di aiuto:

    http://blog.myspace.cn/index.cfm?fus...ogID=400009761

    Fammi sapere.

  8. #8
    codice:
    #include <stdio.h>
    #include <dirent.h>
    #include <sys/stat.h>
    
    void sansone(const char *directory)
    	{
    		DIR *fh;
    		struct dirent *fdata;
    		char source[1000];
    		struct stat buf;
    		if ((fh = opendir (directory)) != NULL)
       		{
    			puts("\nElenco directory:\n");
    			while ((fdata = readdir (fh)) != NULL)
          			{
    				//scarta le directory . e ..
    				if (!strcmp (fdata->d_name, ".") || !strcmp (fdata->d_name, ".."))
                				continue;//salta al prossimo giro
                   			// Verifica se si tratta di una subdir
             			sprintf (source, "%s/%s", directory, fdata->d_name);
             			stat (source, &buf);
    /***********************************************************************************/
    				puts("directory");
    		       		printf("%s\n", source);
    				puts("inserisci un carattere");
    				getchar();
    /***********************************************************************************/			
             			if (S_ISDIR(buf.st_mode))
             			{
    /***********************************************************************************/
    					puts("prima sotto directory\n");
    					getchar();
    
    					sansone(source);
    /***********************************************************************************/	
    
    				}
    			}
    
          			closedir (fh);
    		}
    
    	}
    
    /*********************************** 
     * main
     **********************************/
    int main ()
    {
    	
    	const char *home = "/home"; //directory home dove si mettono i file
    	sansone (home);
    
    return 0;
    }
    Così mi sembra che funzioni, se ci sono errori vedremo...
    ora devo solo usare l'elenco

  9. #9
    Ora come faccio, sempre in linux, a sapere la dimensione e la data di ultima modifica di un file?

  10. #10
    trovato

    struct stat {
    dev_t st_dev; /* device */
    ino_t st_ino; /* inode */
    mode_t st_mode; /* protection */
    nlink_t st_nlink; /* number of hard links */
    uid_t st_uid; /* user ID of owner */
    gid_t st_gid; /* group ID of owner */
    dev_t st_rdev; /* device type (if inode device) */
    off_t st_size; /* total size, in bytes */
    unsigned long st_blksize; /* blocksize for filesystem I/O */
    unsigned long st_blocks; /* number of blocks allocated */
    time_t st_atime; /* time of last access */
    time_t st_mtime; /* time of last modification */
    time_t st_ctime; /* time of last change */
    };

    grazie
    GaPil

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2024 vBulletin Solutions, Inc. All rights reserved.