C Board  

Go Back   C Board > General Programming Boards > C++ Programming

Reply
 
LinkBack Thread Tools Display Modes
Old 04-29-2008, 08:59 AM   #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!
pastitprogram is offline   Reply With Quote
Old 04-29-2008, 09:00 AM   #2
Kernel hacker
 
Join Date: Jul 2007
Location: Farncombe, Surrey, England
Posts: 15,686
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.
matsp is offline   Reply With Quote
Old 04-29-2008, 09:18 AM   #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
pastitprogram is offline   Reply With Quote
Old 04-29-2008, 09:22 AM   #4
3735928559
 
Join Date: Mar 2008
Posts: 662
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 '%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 11:48 AM.
m37h0d is offline   Reply With Quote
Old 04-29-2008, 09:23 AM   #5
3735928559
 
Join Date: Mar 2008
Posts: 662
also, NB: directoryPath+filename = filepath
m37h0d is offline   Reply With Quote
Old 04-29-2008, 09:39 AM   #6
3735928559
 
Join Date: Mar 2008
Posts: 662
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;
}
m37h0d is offline   Reply With Quote
Old 04-29-2008, 10:00 AM   #7
Mysterious C++ User
 
Join Date: Oct 2007
Posts: 14,099
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).
__________________
Using: Microsoft Windows™ 7 Professional (x64), Microsoft Visual Studio™ 2008 Team System
I dedicated my life to helping others. This is only a small sample of what they said:
"Thanks Elysia. You're a programming master! How the hell do you know every thing?"
Quoted... at least once.
Quote:
Originally Posted by cpjust
If C++ is 2 steps forward from C, then I'd say Java is 1 step forward and 2 steps back.
Elysia is offline   Reply With Quote
Old 04-29-2008, 11:12 AM   #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
pastitprogram is offline   Reply With Quote
Old 04-29-2008, 11:16 AM   #9
Mysterious C++ User
 
Join Date: Oct 2007
Posts: 14,099
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.
__________________
Using: Microsoft Windows™ 7 Professional (x64), Microsoft Visual Studio™ 2008 Team System
I dedicated my life to helping others. This is only a small sample of what they said:
"Thanks Elysia. You're a programming master! How the hell do you know every thing?"
Quoted... at least once.
Quote:
Originally Posted by cpjust
If C++ is 2 steps forward from C, then I'd say Java is 1 step forward and 2 steps back.

Last edited by Elysia; 04-29-2008 at 11:18 AM.
Elysia is offline   Reply With Quote
Old 04-29-2008, 11:47 AM   #10
3735928559
 
Join Date: Mar 2008
Posts: 662
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.
m37h0d is offline   Reply With Quote
Old 04-29-2008, 11:58 AM   #11
3735928559
 
Join Date: Mar 2008
Posts: 662
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?
m37h0d is offline   Reply With Quote
Old 04-29-2008, 03:22 PM   #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.
pastitprogram is offline   Reply With Quote
Old 04-29-2008, 03:33 PM   #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();
pastitprogram is offline   Reply With Quote
Old 04-30-2008, 09:58 AM   #14
3735928559
 
Join Date: Mar 2008
Posts: 662
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.
m37h0d is offline   Reply With Quote
Old 04-30-2008, 10:25 AM   #15
Registered User
 
Join Date: Jan 2005
Posts: 7,139
>> void processFile(ifsteam file)
Note that since fstreams cannot be copied, this should be:
Code:
void processFile(ifsteam& file)
Daved is offline   Reply With Quote
Reply

Thread Tools
Display Modes

Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
accessing sequential files "newbie" babyray C++ Programming 2 05-12-2009 03:08 AM
Share folder & files and setting permission on C# over the internet b007 C# Programming 0 11-09-2008 02:34 AM
Accessing files from a C program. Sea (C) Maniac C Programming 13 12-21-2007 05:50 PM
Accessing a variable in several functions in several files Isometric C Programming 2 11-28-2003 09:23 AM
How To Make The Program Installed In Program Files Folder? javacvb Windows Programming 4 11-05-2003 05:33 PM


All times are GMT -6. The time now is 02:21 PM.


Powered by vBulletin® Version 3.8.1
Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.3.0 RC2

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