How to get file names under a folder in C++

As per my earlier post How to transform between a double date-time and std::string in C++, some things are surprisingly hard in C++, especially compared to writing in a .NET language. I recently tracked down this useful snippet of code on the internet in order to recursively build a list of files matching some file extension under a folder. This only compiles on Windows – if you want something cross-platform, look at boost (I wanted to avoid bringing the boost filesystem library into my project as yet another dependency).

void accumulate_files(
  const std::string& folder,
  const std::string& extension,
  std::vector<std::string>& file_names )
{
  std::ostringstream oss;
  oss << folder << "\\";
  std::string search_path = oss.str();

  WIN32_FIND_DATA fd;
  HANDLE hFind = ::FindFirstFile( search_path.c_str(), &fd );
  if( hFind != INVALID_HANDLE_VALUE)
  {
    do
    {
      std::string file_name = fd.cFileName;
      std::ostringstream full_file_name;
      full_file_name << folder << "\\" << file_name;

      if ( boost::algorithm::ends_with( file_name, extension ) )
      {
        file_names.push_back( file_name );
      }
      else if ( file_name != "." && file_name != ".." && !file_name.empty() )
      {
        // Recursively call into next directory
        accumulate_files( full_file_name.c_str(), extension, file_names );
      }
    }
    while( ::FindNextFile(hFind, &fd) );

    ::FindClose(hFind);
  }
}

For production code, you’d also want to wrap the file handle in a smart pointer to ensure it gets closed properly for exception safety.

4 Comments

Filed under C++, C++ Code, Programming

cpplinq – functional style for C++ using lambdas

I’ve just tried out CppLinq, a C++11 library that brings LINQ-style syntax into scope for C++ programmers that are used to writing code in a functional style. I’ve been using C++11 lambdas with STL algorithms like foreach, transform, accumulate – but this syntax using where, for_each, sum and ‘>>’ to chain commands together is so much neater. In fact, it brings C++11 style very close to the succinct F# piping style that is so popular.

To use cpplinq, you can just download a single header file and include it in your code. Awesome – having just battled for hours to use some other 3rd party library which required multiple libs, source files and compiler switches, this is so easy by comparison.

This Dr Dobbs article has several code examples which act as an simple tutorial.

1 Comment

Filed under C++, Programming

Book Review – Riding Rockets, Mike Mullane

Riding Rockets, Mike MullaneHaving first read An Astronaut’s Guide to Life On Earth by Chris Hadfield I was interested to see how this book by another space shuttle astronaut would compare. It’s every bit as good, but in a completely different way. Whilst Chris Hadfield impressed me with his professionalism and values, someone you’d want on your team, Mike Mullane came over as more of a laugh and a guy with whom you’d enjoy a beer. But behind the terrible jokes and politically incorrect attitude, the book reveals a man with great pride, a drive to be the best and a lot more sensitivity to his colleagues and family than I first suspected. Coupled with the author’s insight into historical events concerning NASA and the shuttle program, this is a brilliant book.
Five Stars

Leave a comment

Filed under Book Review

How to emulate C++11’s ‘enum class’ in C++03

One of many neat features in C++11 is the introduction of ‘enum class’ – this addresses problems arising from enum declarations such as scoping (the enum cases leak in the same scope as the enum type) and implicit conversion to integer. See Stroustrup’s C++11 FAQ for more details.

However, in the papers that motivated the new language feature (N1513 and N2347) they discuss the current workarounds for C++03. One such workaround is to define a class to represent the enum type – it’s much more verbose than the new C++11 feature, but it solves the scoping and conversion issues.

// Header file
class Weekday
{
private:
  // Note that the private enum cases have underscores to differentiate
  // from the public cases
  typedef enum Weekday_ { Mon_, Tues_, Wed_, Thurs_, Fri_, Sat_, Sun_ };
  Weekday_ value_;

public:
  static const Weekday Mon, Tues, Wed, Thurs, Fri, Sat, Sun;
  explicit Weekday( const Weekday_& value ) : value_( value ){}

  bool operator<( const Weekday& rhs ) const { return this->value_ < rhs.value_; }
  bool operator==( const Weekday& rhs ) const { return this->value_ == rhs.value_; }
  bool operator!=( const Weekday& rhs ) const { return !(this->operator==(rhs)); }
};

// Source file
// Definitions for the public Weekday instances 
// in terms of the private enum
const Weekday Weekday::Mon( Mon_ );
const Weekday Weekday::Tues( Tues_ );
const Weekday Weekday::Wed( Wed_ );
const Weekday Weekday::Thurs( Thurs_ );
const Weekday Weekday::Fri( Fri_ );
const Weekday Weekday::Sat( Sat_ );
const Weekday Weekday::Sun( Sun_ );

That’s it – I’ve been using this recently and it works pretty well. I also added a “to_int()” member and a static “from_int()” member to explicitly convert bewteen the enum class and integers – the implementation is simply a switch over the enum cases.

8 Comments

Filed under C++, C++ Code, Programming

Restaurant Review: Clos Maggiore, Covent Garden, London

Conservatory at Clos Maggiore
I had a lovely birthday dinner at Clos Maggiore, near Covent Garden in London. This restaurant is one where you have to book long in advance (in my experience, at least a couple of months) – but it was worth the wait. For a romantic occasion, it would be hard to beat the conservatory, with its blossom trees and roaring wood fire. The menu was excellent, and the service impeccable (if slightly arrogant – when I commented to our waiter “It’s a very good menu”, he replied “No, it’s an excellent menu”). Every dish was superb – I can vouch that the braised shoulder of rabbit (starter), the guinea fowl (main) and chocolate fondant were all exceptional. As an extra touch, for my birthday, they piped a suitable greeting on the dessert plate in chocolate (and again for the petit fours with coffee).
Five Starts

Leave a comment

Filed under Restaurant Review

Book Review: The Panther, Nelson DeMille

The Panther, Nelson DeMilleThis John Corey thriller from Nelson DeMille has all the usual ingredients to make a great read – thrust Corey into a highly pressured world where gun play is the norm; include his wife, the lovely Kate Mayfield, to offset the crass and politically incorrect commentary from Corey; throw in an arch-villain as the nemesis for this adventure; finesse with conspiracy theories regarding Corey’s historical emnity with the CIA. The scene setting in Yemen was vivid and had the hallmarks of DeMille’s attention to detail, and yet, this book over-stayed its welcome by a couple of hundred pages. 20130418-193203.jpg

Leave a comment

Filed under Book Review

How to transform between a double date-time and std::string in C++

One of the attractions of writing software using the .NET framework is the wealth of support for doing simple things like translating between different data formats. These tasks are typically much harder to achieve in C++ due to the lack of an equivalent framework. One such task that I came across the other day is that date-times are often represented by a double in Windows, where the integer part represents the date since some epoch and the fractional part is the time as a fraction of 24 hours. Even with access to the Boost library, I still had to do some work to produce a simple transformation in C++.

#include <boost/format.hpp>
#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>

typedef double DateTime;

namespace
{
  boost::gregorian::date parse_date( DateTime date_time )
  {
      boost::gregorian::date dt = boost::date_time::parse_date<boost::gregorian::date>( "1899-12-30", boost::date_time::ymd_order_iso );
      dt += boost::gregorian::date_duration( static_cast<long>( floor(date_time) ) );
  }

  boost::posix_time::time_duration parse_time( DateTime date_time )
  {
    double fractionalDay = date_time - floor(date_time);
    long milliseconds = static_cast<long>( floor( fractionalDay * 24.0 * 60.0 * 60.0 * 1000.0 + 0.5) );
    return boost::posix_time::milliseconds( milliseconds );
  }
}

std::string to_date_string( DateTime date_time )
{
  boost::gregorian::date dt = parse_date( date_time );
  return (boost::format( "%4-%02d-%02d" ) % dt.year() % dt.month().as_number() % dt.day().as_number()).str();
}

DateTime from_date_string( const std::string& value )
{
  boost::gregorian::date epoch = boost::date_time::parse_date<boost::gregorian::date>( "1899-12-30", boost::date_time::ymd_order_iso);
  boost::gregorian::date dt = boost::date_time::parse_date<boost::gregorian::date>( value, boost::date_time::ymd_order_iso);

  boost::gregorian::date_duration diff = dt - epoch;
  return diff.days();
}

std::string to_date_time_string( DateTime date_time )
{
  boost::gregorian::date date_part = parse_date( date_time );
  boost::posix_time::time_duration time_part = parse_time( date_time );

  long long fractional_seconds = time_part.fractional_seconds();
  boost::date_time::time_resolutions resolution = time_part.resolution();
  if ( resolution == boost::date_time::micro )
  {
    fractional_seconds /= 1000;
  } 
  else
  {
    if (resolution != boost::date_time::milli)
      throw std::logic_error( "Unexpected time resolution" );
  }

  return (boost::format( "%d-%02d-%02d %02d:%02d:%02d.%03d" )
    % date_part.Year() % date_part.month().as_number() % date_part.day().as_number()
    % time_part.hours() % time_part.minutes() % time_part.seconds() % fractional_seconds ).str();
}

DateTime from_date_time_string( const std::string& value )
{
  DateTime date = from_date_string( value );
 
  boost::posix_time::ptime t = boost::posix_time::time_from_string( value );
  double milliseconds = static_cast<double>(t.time_of_day().total_milliseconds());

  return date + (milliseconds / 24.0 / 60.0 / 60.0 / 1000.0);
}

Please comment if you know a more straight-forward way to achieve this transformation, especially using Boost. Syntactically, the code could be simplified using C++11 auto, but I’ve spelt out the types explicitly throughout because I found it helpful to see which parts of the boost library are being used.

1 Comment

Filed under C++, C++ Code, Programming

Book Review – An Astronaut’s Guide to Life On Earth, Chris Hadfield

An Astronaut's Guide to Life on Earth, Chris HadfieldI first saw Chris Hadfield on the excellent Stargazing Live on the BBC and on the strength of that appearance I thought his book would be well worth reading. Despite his many achievements and talents, the book paints him as a humble guy who’s keen to contribute but at pains not to hinder (read his chapter on “Aim to be a Zero” and you’ll get the idea). This book has much to say on the importance of working in a team towards a common goal – I would recommend it alongside How to Win Friends and Influence People for anyone embarking on life in the corporate world.
Four stars

1 Comment

Filed under Book Review

Book Review – Never Go Back, Lee Child

Never Go Back, Lee ChildThis story was long awaited, partly because the author has been building up to the meeting of Jack Reacher with Susan Turner and his journey across America to Virginia for several books – this association started in the book 61 Hours, so definitely worth reading that one and before this. On the other hand, this book is one of the best Jack Reacher thrillers, so you might not want to wait. I was waiting to read this in paperback, but was delighted to receive it in a beautiful hardcover edition for my birthday.

I prefer Jack Reacher novels when he works with an accomplice, often a woman, to solve a case and hand out his own brand of justice to the perpetrators. Never Go Back fits the bill and matches The Enemy for excitement and daring plot as a result. There are other plot twists – this book is all about Reacher’s past coming back to haunt him. Does he have a child? Has one of his many violent episodes resulted in a conviction that will see him jailed? Will his previous service in the army see him forcibly conscripted to serve his country again? I tried hard to pace myself reading this one, having polished off other Reacher novels in a couple of days and then having a long wait for the next one. Unfortunately, once I was a few chapters in, I was hooked and as usual sped through it. The compelling question was – having gone back, would Reacher leave again? Or would he finally have re-discovered a life for which it was worth settling down?

Five Stars

1 Comment

Filed under Book Review

iWatch rumours

I wonder if Apple realise just how much expectations are mounting regarding the launch of an iWatch? When I first heard about it, I loved the idea and the prospect without having a clue what it would do (a bit like the daughter of a colleague who asked for an iPod for Christmas and when he asked what she would use it for replied: “I dunno, I just want one”).

Now, a few months on, my expectations are higher. I want it to look like this:

20140408-183611.jpg

And I want it to monitor my health and fitness, act as a heart rate monitor at the gym so I can exercise optimally, measure my activity during the day like a Nike fuel band, and interface to Google maps so that I can glance at my watch for directions instead of walking along holding out my smart phone.

Maybe all of these expectations will be off the mark – in which case, someone else will benefit from all the marketing that’s going on and Apple will lose out.

Leave a comment

Filed under Musing