Link to home
Start Free TrialLog in
Avatar of tkrokowski
tkrokowski

asked on

Scanning a Directory in Visual C++

I need to write a program that compiles several files into one big file so I can do work on that big file. I'm fairly new to windows programming and am having a hard time figuring out how to scan a directory. The directory I need to scan will contain a type of file with a .dat extension and nothing else. I need to find the first file, place it in the bigger file, and then delete it. I can handle putting it in the bigger file and deleting it but I have not had any success scanning the directory and selecting files. Any help would be really appreciated!
Avatar of gj62
gj62

Standard C++ provides no mechanism for searching directories or for deleting files.  It must be done using an OS-specific technique.  So we need to know what OS you are using.

Here's an example (cut from an earlier EE post) for WINDOWS:

#include <stdio.h>
#include <io.h>
#include <time.h>

void main( void )
{
    struct _finddata_t c_file;
    long hFile;

    /* Find first .c file in current directory */
    if( (hFile = _findfirst( "*.c", &c_file )) == -1L )
       printf( "No *.c files in current directory!\n" );
   else
   {

   /* do something with file */
            /* Find the rest of the .c files */
            while( _findnext( hFile, &c_file ) == 0 )
            {
  /* do something with remaining files */
            }

       _findclose( hFile );
   }
}
ASKER CERTIFIED SOLUTION
Avatar of Fallen_Knight
Fallen_Knight

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Slight modification - ANSI C provides for remove() to delete a file, and,  of course, can be called in C++
Avatar of tkrokowski

ASKER

Let me clarify my original question further by saying that this program is being developed in Microsoft Visual C++ 6.0.
Let me clarify my original question further by saying that this program is being developed in Microsoft Visual C++ 6.0.
That was the general premise of what I needed to do. Good job! I tweaked the code a little...



#include <iostream>
#include <windows.h>

#include <vector>
#include <string>
using namespace std;



vector<string> ListDirContents(char *path) {
    int i=0, files;
   vector<string> list;
    WIN32_FIND_DATA find_data;
    HANDLE hnd;

    find_data.dwFileAttributes = FILE_ATTRIBUTE_NORMAL;
    if((hnd = FindFirstFile(path, &find_data)) == INVALID_HANDLE_VALUE)
         return list; //no flies or error
    do
     {
         list.push_back( find_data.cFileName );
     }
    while(FindNextFile(hnd, &find_data));
   
    FindClose(hnd);
    return list;
}

int main()
{
     vector<string> test = ListDirContents("C:\\test\\*.*");

     vector<string>::iterator itr = test.begin();

     cout << test.size() << endl;

     while( itr != test.end() )
     {
          cout << *itr << endl;
          itr++;
     }

     return 0;
}