473,769 Members | 2,234 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Number of files in a directory...

Hello,
I'm writing some C++ code, and I need to be able to find the number of
files in a given directory. Is it possible under AIX4.3.3 with C++ 3.6.4?
I cannot seem to locate anything of this nature in the docs, aside from
creating an array with 'scandir'
(http://publib.boulder.ibm.com/doc_li...ir.htm#A12F0c9)
which will also give me the number of enties in that array. This seems a
little overkill. I'm fairly new to C++, any suggestions would be most
appreciated.
Thanks.

Ken

Jul 22 '05 #1
2 11156
On Sat, 03 Jan 2004 21:04:40 -0500, 73blazer <yo**@ma.com> wrote in
comp.lang.c++:
Hello,
I'm writing some C++ code, and I need to be able to find the number of
files in a given directory. Is it possible under AIX4.3.3 with C++ 3.6.4?
It may be possible under your operating system using your compiler,
provided that they provide some non-standard system-specific
extension. There is no way at all to do this using standard C++, the
topic of this group, which has no support for directory structures at
all.
I cannot seem to locate anything of this nature in the docs, aside from
creating an array with 'scandir'
(http://publib.boulder.ibm.com/doc_li...ir.htm#A12F0c9)
which will also give me the number of enties in that array. This seems a
little overkill. I'm fairly new to C++, any suggestions would be most
appreciated.
Thanks.

Ken


I would suggest posting to a support group for AIX, if there is one,
or the generic news:comp.unix. programmer.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.l earn.c-c++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html
Jul 22 '05 #2
73blazer <yo**@ma.com> writes:
I'm writing some C++ code, and I need to be able to find the number of
files in a given directory. Is it possible under AIX4.3.3 with C++
3.6.4?
Yes. Your C library should have calls for this. Note this is UNIX
functionality: C++ knows nothing about directories. See opendir(3),
readdir(3), closedir(3).
I'm fairly new to C++, any suggestions would be most appreciated.


When I was new to C++, I wrote a "dirstream" class around the above
UNIX library functions, which follows (I believe they are fairly
common). Note: it could be better written, I just hope you find it
useful. Please note it's licensed under the GNU GPL; it may only be
used in other GNU GPL licenced programs.

Now I know a little more, I should have written it to use input
iterators, rather than creating a dirstream extraction operator (á la
ifstream). It should perhaps also throw an exception in the
constructor if opendir() fails, rather than setting an error flag.
I'm not sure what's best here--I don't like throwing exceptions unless
absolutely necessary.

It should also a deque rather than a vector for its dirstream
buffering, but it works quite well in my experience.

If all you want is the number of files, then using the above functions
directly will have less overhead.
Regards,
Roger
// dirstream - C++ stream version of C dirents -*- C++ -*-
// Copyright (C) 2003 Roger Leigh <rleigh AT debian DOT org>
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

#ifndef DIRSTREAM_H
#define DIRSTREAM_H 1

#include <iostream>
#include <vector>
#include <string>

#include <sys/types.h>
#include <dirent.h>

/**
* A class to access information about the files in a directory. This
* is a wrapper around the UNIX opendir(3), readdir(3) and closedir(3)
* functions, which are used to read a stream of "dirents" through
* multiple readdir() calls.
*
* dirstream calls opendir() and closedir() automatically, and
* represents each dirent as a dirstream::dire ntry. Like reading from
* an istream by pulling data out with the >> "extraction operator",
* direntries are also extracted from the dirstream with the >>
* operator.
*/
class dirstream
{
public:

/**
* The constructor.
* @param dir the directory to read.
*/
dirstream(const char *dir);

/**
* The constructor.
* @param dir the directory to read.
*/
dirstream(const std::string& dir);

/// The destructor.
virtual ~dirstream();

/**
* A class to represent an entry in a dirstream. It is a wrapper
* around the dirent structure declared in dirent.h
*
* The direntry is only valid during the lifetime of an open
* dirstream. Once the directory is closed, when the dirstream is
* destroyed, or its close() method called, the direntry can no
* longer be safely used. On many systems, including Linux, this
* does not matter, but the Single UNIX Specification makes no
* garuantees about this.
*/
class direntry
{
public:
/// The constructor.
direntry();

/**
* The constructor.
* @param entry the dirent to initialise the class with.
*/
direntry(const struct dirent *entry);

/**
* The copy constructor.
* @param orig the class to copy.
*/
direntry(const dirstream::dire ntry& orig);

/// The destructor.
virtual ~direntry();

/**
* Get the dirent inode number (d_ino).
* @returns the inode number.
*/
long inode() const;

/**
* Get the file type (d_type).
* @returns the file type.
*/
unsigned char type() const;

/**
* Get the file name (d_name).
* @returns a reference to a string containing the name.
*/
const std::string& name() const;

/**
* Get the dirent.
* @returns a reference to the underlying dirent.
*/
struct dirent& dirent();

private:
/// The underlying dirent the class is wrapping.
struct dirent data;

/// A string form of data.d_name.
std::string sname;
}; // class direntry

/**
* Open a directory for reading. This uses the opendir(3) call to
* open the underlying DIR stream. Any previously open directory is
* closed before opening the new one. The dirstream error state is
* set is the open fails.
* @param dirname the directory to read.
* @see close()
*/
void open(const char *dirname);

/**
* Close the directory. This uses the closedir(3) call to close the
* underlying DIR stream. All cached data is deleted and the error
* state set until open() is called.
* @see open()
*/
void close();

/**
* Check for End Of File.
* @returns true if the dirstream is empty, otherwise false.
*/
bool eof();

/**
* Check for errors. If there is an error, the dirstream is
* unusable until the next open() call.
* @returns true if the dirstream is in an error state, otherwise
* false.
*/
bool bad();

private:

/**
* A list of direntries represents the directory stream as a LIFO
* stack.
*/
std::vector<dir entry> data;

/**
* Read dirents from the underlying DIR stream into the data vector.
* @param quantity the number of dirents to read.
*/
void read(int quantity=1);

/**
* The overloaded extraction operator. This is used to pull
* direntries from a dirstream.
*/
friend dirstream& operator >> (dirstream& in_stream, direntry& entry);

/// The underlying DIR stream
DIR *dir;

/// Error status
bool error;
};

#endif // DIRSTREAM_H
// dirstream - C++ stream version of C dirents -*- C++ -*-
// Copyright (C) 2003 Roger Leigh <rleigh AT debian DOT org>
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

#include <cstring>

#include <errno.h>

#include "dirstream. h"
dirstream::dire ntry::direntry( )
{
// set the dirent data to zero
std::memset(&da ta, 0, sizeof(struct dirent));
sname.clear();
}

dirstream::dire ntry::direntry( const struct dirent *entry)
{
// set the dirent data
std::memcpy(&da ta, entry, sizeof(struct dirent));
sname = data.d_name;
}

dirstream::dire ntry::direntry( const dirstream::dire ntry& orig)
{
memcpy(&data, &orig.data, sizeof(struct dirent));
sname = data.d_name;
}

dirstream::dire ntry::~direntry ()
{
// do nothing
}

long
dirstream::dire ntry::inode() const
{
return data.d_ino;
}

unsigned char
dirstream::dire ntry::type() const
{
return data.d_type;
}

const std::string&
dirstream::dire ntry::name() const
{
return sname;
}

struct dirent&
dirstream::dire ntry::dirent()
{
return data;
}
dirstream::dirs tream(const char *dirname)
{
dir = NULL;
error = false;
open(dirname);
}

dirstream::dirs tream(const std::string& dirname)
{
dir = NULL;
error = false;
open(dirname.c_ str());
}

dirstream::~dir stream()
{
close();
}

void
dirstream::open (const char *dirname)
{
dir = opendir(dirname );
if (dir == NULL)
error = true;
else
error = false;
read();
}

void
dirstream::read (int quantity)
{
int i;

if (dir == NULL)
return;

for (i=0; i<quantity; i++)
{
//std::cerr << "Read one entry" << std::endl;

struct dirent* entry;
entry = readdir(dir);

if (entry == NULL) // EOF or error
{
//std::cerr << "Directory read error: ";
if (errno == EBADF) // error
{
error = true;
//std::cerr << "bad directory stream";
}
//else
//std::cerr << "end of stream";
//std::cerr << std::endl;
return;
}

direntry newentry(entry) ; // make a direntry
data.push_back( newentry); // push onto the end of the list
}
}

// close the directory
// this also clears all the direntry data
void
dirstream::clos e()
{
if (dir)
closedir(dir); // don't throw an exception -- it could be called
// in the destructor
dir = NULL;
data.clear(); // clear all data
error = true;
}
bool
dirstream::eof( )
{
if (data.empty())
return true;
return false;
}

bool
dirstream::bad( )
{
return error;
}
dirstream& operator >> (dirstream& in_stream, dirstream::dire ntry& entry)
{
in_stream.read( ); // read a new entry
if (in_stream.eof( ) == false) // not at end of file
{
// std::cerr << "Assigning direntry" << std::endl;
entry = in_stream.data. front(); // assign next direntry to entry
in_stream.data. erase(in_stream .data.begin()); // remove the entry
// std::cerr << in_stream.data. size() << std::endl;
}
else // blank the direntry
std::memset(&en try, 0, sizeof(dirstrea m::direntry));

return in_stream;
}
--
Roger Leigh

Printing on GNU/Linux? http://gimp-print.sourceforge.net/
GPG Public Key: 0x25BFB848. Please sign and encrypt your mail.
Jul 22 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
1708
by: David T. Ashley | last post by:
Hi, PHP allows the "library" which can contain an arbitrary number of include files. Can I put all the include files right in this directory, or should I create subdirectories? My question comes about because I understand that *nix systems begin to run into performance difficulties at around 200 files in a directory (linear
4
11848
by: Bart Plessers \(artabel\) | last post by:
Hello, I have an asp script that lists the files in a directory: CurrentPATH = "c:\temp\" Set oFSO = CreateObject("Scripting.FileSystemObject") Set oFolder = oFSO.GetFolder(CurrentPATH) Set oFolderContents = oFolder.Files For Each oFileItem in oFolder.Files .....
2
3653
by: Amy L. | last post by:
I am working on some code that will be used in a Windows Service that will monitor specific files in a queue. I would like to get an integer value of the amount of specfic files in a directory. Now I have been using this code to get what I need. private DirectoryInfo di ; di = new DirectoryInfo( @"c:\temp" ) ; int files_in_directory_value = di.GetFileSystemInfos( "*.abc" ).Length ;
1
20077
by: supster | last post by:
EDIT: I no longer need only specific file types in a directory, just the total number of files! Is there a more efficient way other than this: string files = Directory.GetFiles(path); count = files.length; It seems like such a waste to have to create a full array of strings,
1
9262
by: jj | last post by:
Hi folks: I can get the list of files in a certain directory by using Directory.GetFiles("c:\temp"). But I want to get the number of files (ex. 20) within a directory including all subdirectories. I don't want to scan through the whole recursively and count. Is there a way? Thanks John
1
4638
by: sasikumar | last post by:
i have created a new folder inside project(say update for storing update files for software) how can i get total number of files in that folder.what will be full path for accessing that folder.(path compatibile for use in system.io)
5
1808
by: bhu | last post by:
Hi any idea how to get a set of files from a Directory, if a Directory contains 100 files i want to access 10 file at a time move it to a different directory , grab the next 10 do the same, Also is there a way to get the First Set of File by the Date and time Stamp FIFO thanks bhu
8
6393
by: theCancerus | last post by:
Hi All, I am not sure if this is the right place to ask this question but i am very sure you may have faced this problem, i have already found some post related to this but not the answer i am looking for. My problem is that i have to upload images and store them. I am using filesystem for that. setup is something like this, their will be items/groups/user each can
1
4538
by: briggs | last post by:
Hi All, I need to take the count of txt and bak files present in all the directory.for eg if we assume there are two directoies say(test1, test2), I need to collect the count(of txt and bak files) and print it out.. I tried the below code, but could not achieve what I need.Can someone help me on the same. Prg: ($dir, $extension) = @ARGV; $dir = "." unless $dir;
0
9424
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10051
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9866
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8879
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7413
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6675
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5310
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3968
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2815
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.