accessing all files in a folder.

This is a discussion on accessing all files in a folder. within the C++ Programming forums, part of the General Programming Boards category; hi everyone, im stuck on a task ive being trying to work out now for nearly 1 month. Its really ...

  1. #1
    Registered User
    Join Date
    Apr 2008
    Posts
    99

    accessing all files in a folder.

    hi everyone, im stuck on a task ive being trying to work out now for nearly 1 month. Its really starting to annoy the heck out of my. I have a program that basically does the following

    1) user enters the path of a file to be examined
    2)User enters the path of an output file for the examination results
    3) my prog does what i want it to do and outputs the file examination fine.

    I like my program and it does what i want it to do......sort of.


    To make it more efficent i was trying to get it so that the user can examine multiple files in a folder instead of just 1 at a time. In turn i could output multiple output files and the process becomes alot better. This is where im totally getting stuck and have been for some time. I got to the point of listing all the files in the folder but i know this is no where near what i want it to do.

    If i could get it so the user can point to a folder containing all the files. Then the user can point to an output folder. Then my process could automate through all the files in the folder outputing all the examined output files that would be smashing.

    Can anyone offer any help or advice? Believe me it would be much appreciated i feel like ive been working on this forever!

  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Yes, that sounds like a plan.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  3. #3
    Registered User
    Join Date
    Apr 2008
    Posts
    99
    kool im glad it sounds like it could work. Thing is i can list the files in a folder that the user selects, but after this point i am unable to get a hold on each indiviual file and loop through all the files examining and outputing each one, one at a time. I just cant seem to get this to work

  4. #4
    3735928559
    Join Date
    Mar 2008
    Location
    RTP
    Posts
    839
    these helpfiles should be relevant to your interests.


    Header File

    dirent.h

    Category

    Directory Control Routines

    Prototype

    DIR *opendir(const char *dirname);

    wDIR *wopendir(const wchar_t *dirname);

    Description

    Opens a directory stream for reading.

    opendir is available on POSIX-compliant UNIX systems.

    The opendir function opens a directory stream for reading. The name of the directory to read is dirname. The stream is set to read the first entry in the directory.

    A directory stream is represented by the DIR structure, defined in dirent.h. This structure contains no user-accessible fields. Multiple directory streams can be opened and read simultaneously. Directory entries can be created or deleted while a directory stream is being read.

    Use the readdir function to read successive entries from a directory stream. Use the closedir function to remove a directory stream when it is no longer needed.

    Return Value

    On success, opendir returns a pointer to a directory stream that can be used in calls to readdir, rewinddir, and closedir.

    On error (If the directory cannot be opened), the functino returns NULL and sets the global variable errno to

    ENOENT The directory does not exist
    ENOMEM Not enough memory to allocate a DIR object


    Code:
    /* opendir.c - test opendir(), readdir(), closedir() */
     
    #include <dirent.h>
    #include <stdio.h>
    #include <stdlib.h>
     
    void scandir(char *dirname)
    {
       DIR *dir;
       struct dirent *ent;
     
       printf("First pass on '&#37;s':\n",dirname);
       if ((dir = opendir(dirname)) == NULL)
       {
         perror("Unable to open directory");
         exit(1);
       }
       while ((ent = readdir(dir)) != NULL)
         printf("%s\n",ent->d_name);
     
       printf("Second pass on '%s':\n",dirname);
    
       rewinddir(dir);
       while ((ent = readdir(dir)) != NULL)
         printf("%s\n",ent->d_name);
       if (closedir(dir) != 0)
         perror("Unable to close directory");
    }
     
    void main(int argc,char *argv[])
    {
       if (argc != 2)
       {
         printf("usage: opendir dirname\n");
         exit(1);
       }
       scandir(argv[1]);
       exit(0);
    }
    Last edited by m37h0d; 04-29-2008 at 12:48 PM.

  5. #5
    3735928559
    Join Date
    Mar 2008
    Location
    RTP
    Posts
    839
    also, NB: directoryPath+filename = filepath

  6. #6
    3735928559
    Join Date
    Mar 2008
    Location
    RTP
    Posts
    839
    i just realized i didn't have a scandir function myself, but i will likely need one in the near future.

    this should give you the basic idea of what you want to do. hope this helps

    Code:
    void doStuff(FILE *file)
    {
            //do stuff here
    }
    
    int main()
    {
            const char *dirPath ="C:\\";
            DIR *d = opendir(dirPath);
            struct dirent *ent;
            if(d)
            {
                    ent = readdir(d);
                    while(ent)
                    {
                            char *filePath = strcpy(filePath,dirPath);
                            strcat(filePath,"\\");
                            strcat(filePath,ent->d_name);
                            FILE *file = fopen(filePath,"r");
                            if(file)
                            {
                                    doStuff(file);
                            }
                            ent = readdir(d);
                    }
            }
            return 0;
    }

  7. #7
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Posts
    23,022
    Avoid putting descriptions, replies or any other weird sort of information in code blocks.
    The text won't be wrapped. Currently, it's even extending beyond my own screen resolution which is 1920, which is nothing to scoff at (and that makes your text very long).
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  8. #8
    Registered User
    Join Date
    Apr 2008
    Posts
    99
    hi again, ive had a botch around and ive got it so the user can enter a folder path in, then it will run through the folder printing out the complete path of every file in that folder - stored in variable 'filepath'



    Code:
    
      DIR           *d;
      struct dirent *dir;
    
    //enter directory path here
    
    cout << "Enter the name OF FOLDER: ";
        string g_1;
       getline( cin, g_1 );
    
    d = opendir ( g_1.c_str() );
     
    
     if ( d )
      {
        
    
    	while ( ( dir = readdir ( d ) ) != NULL )
       
     {
    
    string filepath;
    
          string g =  dir->d_name;
          cout << g << endl;
    
    string filename1 = g_1 + g; //concat the paths
    fstream read ( filename1.c_str() );
    filepath = filename1;
    
    cout << filepath << endl;
     
     ifstream infil( filepath.c_str(), ios::binary );
    
        
    
     read.close();
    
        }
       
     closedir ( d );
     
     }
    
      getchar();
      return ( 0 );


    somehow i need to get the path of each file in the folder out of the loop each time and into main so that i can create a ifstream with the path variable so i can preform my calculations on the file each time.................i hope that made sense. Basically i cant access my ifstream in the loop so i need to pass it out of the loop each time it gets the path of a new file. Is there a way to return it to somewhere i can access it?


    thanks

  9. #9
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Posts
    23,022
    I'm sorry, but the code is difficult to read. You may need to indent it a little better.
    You can try to make it look more like the example @ http://cpwiki.sf.net/Indentation
    Or try reading the in-depth guide at http://cpwiki.sf.net/User:Elysia/Indentation

    I don't really get your question either. But what's wrong with your current way?
    Also, the readdir function seems mysterious. Does it return allocated memory (via new)?
    And why does it accept a pointer? I think it should take a reference, and probably another reference to a buffer to store data if anything.
    The "struct" keyword is also optional when defining variables from structs.
    Last edited by Elysia; 04-29-2008 at 12:18 PM.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  10. #10
    3735928559
    Join Date
    Mar 2008
    Location
    RTP
    Posts
    839
    dirent.h

    Category

    Directory Control Routines

    Prototype

    struct dirent *readdir(DIR *dirp);

    struct wdirent *wreaddir(wDIR *dirp)

    Description

    Reads the current entry from a directory stream.

    readdir is available on POSIX-compliant UNIX systems.

    The readdir function reads the current directory entry in the directory stream pointed to by dirp. The directory stream is advanced to the next entry.

    The readdir function returns a pointer to a dirent structure that is overwritten by each call to the function on the same directory stream. The structure is not overwritten by a readdir call on a different directory stream.

    The dirent structure corresponds to a single directory entry. It is defined in dirent.h and contains (in addition to other non-accessible members) the following member:

    char d_name[];

    where d_name is an array of characters containing the null-terminated file name for the current directory entry. The size of the array is indeterminate; use strlen to determine the length of the file name.

    All valid directory entries are returned, including subdirectories, “.” and “..” entries, system files, hidden files, and volume labels. Unused or deleted directory entries are skipped.

    A directory entry can be created or deleted while a directory stream is being read, but readdir might or might not return the affected directory entry. Rewinding the directory with rewinddir or reopening it with opendir ensures that readdir will reflect the current state of the directory.

    The wreaddir function is the Unicode version of readdir. It uses the wdirent structure but otherwise is similar to readdir.

    Return Value

    On success, readdir returns a pointer to the current directory entry for the directory stream.

    If the end of the directory has been reached, or dirp does not refer to an open directory stream, readdir returns NULL.

  11. #11
    3735928559
    Join Date
    Mar 2008
    Location
    RTP
    Posts
    839
    Quote Originally Posted by pastitprogram View Post
    hi again, ive had a botch around and ive got it so the user can enter a folder path in, then it will run through the folder printing out the complete path of every file in that folder - stored in variable 'filepath'

    somehow i need to get the path of each file in the folder out of the loop each time and into main so that i can create a ifstream with the path variable so i can preform my calculations on the file each time.................i hope that made sense. Basically i cant access my ifstream in the loop so i need to pass it out of the loop each time it gets the path of a new file. Is there a way to return it to somewhere i can access it?


    thanks
    so you pass either the ifstream or the string filepath as an argument, what's the problem?

    and why can't you access the ifstream? are you saying you literally cannot, or it's just going to be a mess?

  12. #12
    Registered User
    Join Date
    Apr 2008
    Posts
    99
    what im saying is at present my program is set up as follows

    first a standard ifstream is declared in main for the file to be examined.
    This stream then gets passed to a while loop to preform a search, which inturn passes my results to a function.

    somehow i need to break my ifstream out of the loop each time it reads a new file in a folder, so that all the processes can take place.

    I hope this is making sense. Im probably doing things the messy and hard way because my programming skillls arnt the best but i dont really want to start changing things too much. I could post all my code but i dont think it would be beneficial as most of it does not apply to what im trying to do.

  13. #13
    Registered User
    Join Date
    Apr 2008
    Posts
    99
    I have put the bare bones essential parts of my code in this post to see if anyone could offer advice. Currently its uses the ifstream 'infile' to run and only handles 1 file. If i could use the ifstream 'filepath', that contains a path for every file in a folder, my problems would be solved!

    thanks in advance for any advice offered





    Code:
    DIR           *d;
    struct dirent *dir;
    
    
    
    
    //THIS IS MY STRUCTURE IN MAIN THAT RUNS THROUGH ALL FILES IN A DIRECTORY. ITS PROBABLY MESSY BUT IT WORKS
    
    
    cout << "Enter the name OF FOLDER: ";
    string g_1;
    getline( cin, g_1 );
    d = opendir ( g_1.c_str() );
     
    
     if ( d )
               {
                   while ( ( dir = readdir ( d ) ) != NULL )
       
               {
    
                     string filepath;
    
                    string g =  dir->d_name;
               
                     string filename1 = g_1 + g; //concat the paths
                   
                     filepath = filename1;
     
                      ifstream infile11( filepath.c_str(), ios::binary );
    
       
                       read.close();
    
                       }
       
    
                     closedir ( d );
     
                       }
    
      getchar();
      return ( 0 );
    
    
    
    
    
    
    
       // CURRENTLY I USE THIS IFSTREAM TO MAKE MY PROGRAM WORK FOR JUST ONE FILE I HAVE CUT OUT THE USER INPUT AS IT ISNT REALLY APPLICABLE
    
    
    
       ifstream infile( filename.c_str(), ios::binary );     
    		
    	
    		
    			
    //THIS LOOP PICKS UP THE IF STREAM AND IS THE START OF ALL OF MY PROCESSES. IF I CAN SOMEHOW PASS THE IFSTREAM ''FILEPATH'' TO THIS LOOP FOR EVERY FILE THAT IS FOUND IN A FOLDER THIS WOULD SOLVE ALL MY PROBLEMS
    
    	while(lastPositionFound>=0)
    	{
    		int dataStart;
    		int dataEnd;
    
    		// Find start of data chunk
    		lastPositionFound = find(infile, match_criteria, 2, lastPositionFound);
    
    		dataStart=lastPositionFound;
    
    
    
    		if(lastPositionFound>=0)
    		{
    			lastPositionFound = find(infile, match_criteria1, 1, lastPositionFound);
    			dataEnd = lastPositionFound+1;
    		}
    
    
    		if(lastPositionFound>=0)
    		{
    			// Handle file
    			ExportChunk(infile,outputfilename, dataStart, dataEnd);
    			//outputfilename[12]++;
    		}
    
    	}
    	
    
    	 infile.close();

  14. #14
    3735928559
    Join Date
    Mar 2008
    Location
    RTP
    Posts
    839
    why not just pass the ifstream or filename as an argument to a function?

    Code:
    void processFile(ifsteam file)
    {
            //process file here!
    }
    
    int main()
    {
            DIR *d;
            struct dirent *dir;
            cout << "Enter the name OF FOLDER: ";
            string g_1;
            getline( cin, g_1 );
            d = opendir ( g_1.c_str() );
            if (d)
            {
                    while((dir = readdir(d)) != NULL)
                    {
                            string filepath;
                            string g =  dir->d_name;
                            string filename1 = g_1 + g; //concat the paths
                            filepath = filename1;
                            ifstream infile11( filepath.c_str(), ios::binary );
                            processFile(infile1);
                            read.close();
                    }
                    closedir(d);
            }
            return 0;
    }
    also please indent sanely.

  15. #15
    Registered User
    Join Date
    Jan 2005
    Posts
    7,344
    >> void processFile(ifsteam file)
    Note that since fstreams cannot be copied, this should be:
    Code:
    void processFile(ifsteam& file)

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. accessing sequential files "newbie"
    By babyray in forum C++ Programming
    Replies: 2
    Last Post: 05-12-2009, 04:08 AM
  2. Replies: 0
    Last Post: 11-09-2008, 02:34 AM
  3. Accessing files from a C program.
    By Sea (C) Maniac in forum C Programming
    Replies: 13
    Last Post: 12-21-2007, 05:50 PM
  4. Replies: 2
    Last Post: 11-28-2003, 09:23 AM
  5. How To Make The Program Installed In Program Files Folder?
    By javacvb in forum Windows Programming
    Replies: 4
    Last Post: 11-05-2003, 05:33 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21