473,834 Members | 2,050 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 11163
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
1711
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
11850
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
3654
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
20078
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
9263
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
4639
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
6398
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
4540
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
9799
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9646
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
10795
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10550
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10220
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
9332
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
4427
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
2
3981
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3083
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.