Every Flavour Beans

“The time has come…to talk of many [technologies].” –Lewis Carroll(’The Walrus and the Carpenter’)
Development Tools. Web Frameworks. GNU/Linux. Nokia N800. Video Encoding.

May 31, 2006

C++ Boost Filesystem Library(Part III): Example Programs

Filed under: C++ Boost — tabrez @ 12:34 pm

My earlier posts on C++ Boost Libraries introduced the Boost Filesystem Library and discussed some example programs that make use of it. I discuss two more examples in this post. (Be sure to include the needed boost header files as noted in the earlier posts, including creation of the alias to the boost filesystem namespace: namespace bfs = boost::filesystem; )

1. A function to search for a file.

C++:
  1. // Search for a file with the name 'filename' starting in directory 'dir_path', copy the path of the file in 'pfound' if found, and return true.
  2. // Else return false.
  3. bool find_file(const bfs::path & dir_path, const std::string & file_name, bfs::path & pfound)
  4. {
  5.     if( !exists(dir_path) || !is_directory(dir_path) ) 
  6.         return false;
  7.     bfs::directory_iterator iter(dir_path), end_iter;
  8.     for(; iter!= end_iter; ++iter)
  9.     {
  10.         if( bfs::is_directory(*iter) )
  11.         {
  12.             if( find_file(*iter, file_name, pfound) )
  13.                 return true;
  14.         }
  15.         else if( iter->leaf() == file_name )
  16.         {
  17.             pfound = *iter;
  18.             return true;
  19.         }
  20.     }
  21.     return false;
  22. }

The function first verifies if the path passed in 'path_dir' exists and if it is a directory. Then it creates a 'directory_iterator' object(introduced in the previous post) by passing this path to its constructor. The loop then iterates over all the contents of the directory, and for every sub-directory found, it calls itself recursively passing this new directory as the starting point. Every file that is found is compared with the file that is to be searched(file_name), and if a match is found, the path is copied into 'pfound' and function returns true. If nothing is found by the end of the loop, 'false' is returned. Remember that as discussed earlier, iter->leaf() returns the last part of a path - the file name. Applying indirection operator to the directory_iterator object returns the file it is pointing to.

2. A simple directory listing (ls/dir) program.

C++:
  1. void sls(const bfs::path & p)
  2. {
  3. unsigned long fc=0, dc=0;
  4. if( !bfs::exists(p) )
  5.     std::cout<<"\nFile Not Found:"<<p.native_file_string()<<"\n";
  6.  
  7. else if( !bfs::is_directory(p) )
  8.     std::cout<<"\nFound: " <<p.native_file_string() <<"\n";
  9.  
  10. std::cout<<"In directory:"<<p.native_file_string()<<"\n";
  11. bfs::directory_iterator iter(p), end_iter;
  12. for(; iter != end_iter; ++iter)
  13. {
  14.     try {
  15.         if(bfs::is_directory(*iter))
  16.         {
  17.             ++dc;
  18.             std::cout<<iter->leaf()<<"[Directory]\n";
  19.         }
  20.         else
  21.         {
  22.             ++fc;
  23.             std::cout<<iter->leaf()<<"\n";
  24.         }
  25.     } catch(const std::exception & ex) {
  26.         std::cout<<iter->leaf() <<": " <<ex.what() <<std::endl;
  27.     }
  28.     std::cout<<fc<<" "<<dc<<std::endl;
  29. }  //for
  30. }  //sls

The function simply iterates over all the contents of the directory passed to it(p) and prints every file and directory that is found. [Directory] tag is added to the directory names, and at the end of the program the total count of the files and directories is printed. This program only prints the contents of the directory passed, it doesn't traverse its sub-directories. Can you combine the general idea of the above two examples to create a directory listing program that displays the files of all the sub-directories recursively? You can also print more information about the files by using boost filesystem functions like is_symbolic_link(), file_size(), last_write_time() etc[discussed in the earlier posts].

Most of the examples inspired/taken from the Boost website. The website documentation also contains more help on the various formats in which the paths to the files can be represented. The function 'native_file_string()' used in the Example 2 above returns the path in the native format(using '/' as a file separator on Unix platforms and '\' on Windows platforms, for example). To pass the path names as 'path' objects, use the services from fstream.hpp. All Filesystem library related exceptions are available in exception.hpp. The header convenience.hpp contains a few convenience functions(like change_extension()). You can start from the documentation page on the website for further information.


If you want to receive future posts by email, enter your email address here:

Related Posts:

  • How to Test C++ Boost Installation
  • C++ Boost Filesystem Library(Part II): Example Programs
  • Boost Filesystem Library: Writing Portable C++ Programs to Acess The Filesystem
  • Setting the Stage for C++ Boost
  • Installing C++ Boost on Gentoo and Debian/Ubuntu
  • Installing C++ Boost on SuSE and Fedora
  • Installing C++ Boost on Microsoft Windows for Visual Studio .NET 2003/2005/Orcas

  • May 29, 2006

    Wordpress Plugin and Theme Cheatsheets

    Filed under: General — tabrez @ 5:07 pm

    If you are a plugin or a theme developer for the Wordpress software, then you probably are going to love these two cheatsheets - created as JPG images so that they can be set as a desktop wallpaper! Screenshots for the Plugin cheatsheet and the Theme cheatsheet are available at the headzoo.com website. Send suggestions or any other feedback to the author.

    More cheatsheets related to programming technologies are available here.
    Official google cheatsheet is here but I think you will like this google cheatsheet more.

    For more such cheatsheets, there is always Google Search :)


    If you want to receive future posts by email, enter your email address here:

    Related Posts:

  • Upgrading to Wordpress 2.3 with Zero Downtime!
  • Wordpress Upgrading Experience With Automatic Upgrade Plugin
  • Why I Moved My Blog From Wordpress.com
  • Make OS2008 for N800/N810 Look Beautiful
  • My First Wordpress 2.3 Update Notification and Subversion Upgrade
  • How I Upgraded to Wordpress 2.3 on Live Blog With Zero Downtime
  • What is New in Wordpress 2.3 (Beta 1/2)?

  • May 28, 2006

    C++ Boost Filesystem Library(Part II): Example Programs

    Filed under: C++ Boost — tabrez @ 7:56 pm

    Beyond the C++ Standard Library : An Introduction to BoostContinuing from where I had left in my earlier post containing the basics of the C++ Boost Filesystem Library, below are some example programs that make use of some common facilities available in the Boost Filesystem Library. I assume that all the code snippets shown in this post are properly nested within the main() function apart from including the following things:

    C++:
    1. #include<boost/filesystem/operations.hpp>
    2. #include<iostream>
    3. #include<string>
    4. namespace bfs=boost::filesystem;

    1. Simple program to demonstrate the use of file creation and removal operations:

    C++:
    1. std::cout<<"Enter your choice:\n";
    2. std::cout<<"1. Create folder\n2. Rename File\n3. Remove File\n4. Copy File\n";
    3. char ch;
    4. std::cin>>ch;
    5. std::string name, new_name;
    6. switch(ch)
    7. {
    8.    case '1':
    9.       std::cout<<"Enter folder name:";
    10.       std::cin>>name;
    11.       bfs::create_directory(bfs::path(name));
    12.       break;
    13.    case '2':
    14.       std::cout<<"Enter file name:";
    15.       std::cin>>name;
    16.       std::cout<<"Enter new name:";
    17.       std::cin>>new_name;
    18.       bfs::rename(name, new_name);
    19.       break;
    20.    case '3':
    21.       std::cout<<"Enter file name:";
    22.       std::cin>>name;
    23.       bfs::remove(bfs::path(name));
    24.       break;
    25.    case '4':
    26.       std::cout<<"Enter file name:";
    27.       std::cin>>name;
    28.       std::cout<<"Enter new name:";
    29.       std::cin>>new_name;
    30.       bfs::copy_file(name, new_name);
    31.       break;
    32. }
    33. std::cout<<"Operation finished."<<std::endl;
    34. }

    Pay attention to the following four Boost Filesystem functions used:

    C++:
    1. bfs::create_directory(bfs::path(name));
    2. bfs::rename(name, new_name);
    3. bfs::remove(bfs::path(name));
    4. bfs::copy_file(name, new_name);

    They all do what their function names suggest. Like its always the case with the simple example programs, no error checking is done here ;)

    2. Removing all the files from a directory:

    C++:
    1. std::cout<<"Enter the name of the folder to empty:";
    2. std::string name;
    3. std::cin>>name;
    4. bfs::remove_all(bfs::path(name));
    5. std::cout<<"Operation completed."<<std::endl;

    The other examples needs an introduction to the directory_iterator class which is used to iterate over the contents of a directory. A simple usage looks like this:

    C++:
    1. bfs::path p("folder");
    2. bfs::directory_iterator dir_iter(p), dir_end;
    3. for(;dir_iter != dir_end; ++dir_iter)
    4. {
    5.     std::cout<<(*dir_iter).leaf();
    6. }

    C++ Template Metaprogramming : Concepts, Tools, and Techniques from Boost and Beyond (C++ in Depth Series)A directory_iterator object can be created by passing it a name of a directory. Applying the prefix increment operator(++) to it makes it point to the next file in the directory. Applying the indirection operator(*) returns the file currently being pointed to, as a 'path' object. We call the leaf() method on the returned 'path' object to print the file name. Using 'dir_iter->leaf()' instead of '(*dir_iter).leaf()' has the same effect.

    Using a 'directory_iter' object, we can create a function similar to the 'remove_all()' function that we used in Example 2.
    3. Removing all the files from a directory by iteration:

    C++:
    1. std::cout<<"Enter the name of the folder to empty:";
    2. std::string name;
    3. std::cin>>name;
    4. bfs::path p(name);
    5. if(!bfs::exists(p) || !bfs::is_directory(p))
    6. {
    7.     std::cout<<"Invalid input."<<std::endl;
    8.     exit(-1);
    9. }
    10. bfs::directory_iterator dir_iter(p), dir_end;
    11. for(;dir_iter != dir_end; ++dir_iter)
    12. {
    13.     std::cout<<"Removing file: "<<dir_iter->leaf();
    14.     bfs::remove(*dir_iter);
    15. }
    16. std::cout<<"Operation Completed."<<std::endl;

    Simple error checking is done on the input before calling the remove()function on all the files present in the specified folder. Will follow up with more examples using the Boost Filesystem Library.


    If you want to receive future posts by email, enter your email address here:

    Related Posts:

  • C++ Boost Filesystem Library(Part III): Example Programs
  • How to Test C++ Boost Installation
  • Boost Filesystem Library: Writing Portable C++ Programs to Acess The Filesystem
  • Setting the Stage for C++ Boost
  • Installing C++ Boost on Gentoo and Debian/Ubuntu
  • Installing C++ Boost on SuSE and Fedora
  • Installing C++ Boost on Microsoft Windows for Visual Studio .NET 2003/2005/Orcas

  • May 25, 2006

    Movable Type 3.3 Beta To Be Released On May 31

    Filed under: General, Web — tabrez @ 9:21 pm

    Its close to one year now since the 3.2 version of the Movable Type blog publishing software was released last year. Jay Allen, Product Manager at Six Apart, has announced yesterday that the first beta of the next version of the software, Movable Type 3.3, will be released on May 31.

    Good news: We've got a new version of Movable Type on the way, and we wanted to let you know that the beta is coming soon. We plan to start the Movable Type 3.3 beta test on Wednesday, May 31.

    The highlight this time around about the beta development stage is that a separate blog will be serving as a common place for everyone to keep informed(and get technical support) about the latest developments with the beta product. There is also a tight 3-week deadline for beta testing this time, informs Jay Allen. So whoever is a Movable Type fan and would like to get their hands dirty by test driving its multiple beta versions that would be released in the coming next few weeks, get ready and be prepared for the D-day.
    You can read the announcement here:
    Coming soon: Movable Type 3.3 (beta)

    Update: More details about the new features of the Beta version to be released are here: What's new in Movable Type 3.3?


    If you want to receive future posts by email, enter your email address here:

    Related Posts:

  • PC World’s Humorous Piece On Microsoft, Google, Yahoo’s Beta Services
  • A Visual Tour Of Windows Vista Beta 2 (50+ Screenshots!) (Page 1)
  • A Visual Tour Of Windows Vista Beta 2 (50+ Screenshots!)
  • What is New in Wordpress 2.3 (Beta 1/2)?
  • OS2008 For Nokia N800 Released - Links to Reviews, Resources and First Impressions
  • Installing Grails in Ubuntu GNU/Linux Using Package Manager
  • Installing C#/Mono(.NET)/MonoDevelop/XSP in Ubuntu Gutsy Gibbon(7.10)

  • May 24, 2006

    Should I Be Developing Ajax Applications using Google Web Toolkit(GWT)?

    Filed under: Ajax, General, Web — tabrez @ 5:03 pm

    So why should an Ajax developer be interested in the recently released Google Web Toolkit(GWT)? One possible reason could be to overcome the shortcomings of the typical Ajax web development model as noted in my earlier post. Firstly, a framework always provides a head start to a project, allowing the developers to worry only about writing the application logic; user interface elements, the plumbing work needed for the communication between the client and the server are provided by the framework itself. The more specific benefits of using the Google Web Toolkit are:

    1. The developer is relieved from the thankless job of understanding every single way in which the browsers differ from one another in handling the same web page, allowing them to create websites such that all these web browsers handle a page in (roughly) the same way.
    2. GWT allows the developers to interact with the browser's history stack which means that the Ajax applications created using GWT can allow the users to use the 'Back' and 'Forward' buttons of the web browser and to bookmark the various pages of the website.

      Refer to points 2 & 3 in my earlier post.

    3. Developers can use a more modular and statically typed programming language in Java to create the interface and other components instead of hacking their way out with Javascript. Ultimately, its still the JavaScript code that is generated and served to the web browser, but GWT provides an abstraction layer that shields the developers from having to do much with the JavaScript language. The flip side of this is that for pure interface code, Javascript might offer a more natural solution than Java language when it comes to creating web pages; see the discussion below.

      Refer to point 1 in my earlier post.

      Being able to use Java to create Ajax applications also means better integration with the rest of the Java web development technologies like JSP, JSF, etc(note that code written using GWT uses the Java Web UI class library which is not related to any of the Java standard libraries and this code is statically translated to Javascript and HTML code before making available to the server. Integration would be limited to sharing something like a Java component between a JSP page and the code written using GWT). This may not appeal to those who are using other server-side technologies like PHP and ASP.NET.

      Java language also boasts of better programmer IDEs and tools with good support for Unit Testing and Refactoring. In fact, GWT itself has good JUnit integration through easy to use class libraries in the package com.google.gwt.junit.

      Javascript code can still be embedded within the Java code if only the services of the Javascript language are going to solve a particular problem, by using the Javascript Native Interface(JSNI)(on the lines of JNI). See this for more information.

    4. The biggest advantage of using GWT for creating Ajax applications is the relative ease with which the data can be communicated between the server and the client by just creating serializable Java objects.
    5. Good support for debugging. Eclipse IDE and GWT host mode form a good combination for convenient debugging of the GWT applications.

    Having said all this, I am not a big fan of static translation of one programming language to the other. If it were as unified as in ASP.NET(see ASP.NET WebParts; all the translation happens at run-time), I would have welcomed it whole-heartedly. But different programming languages are created to solve different problems, and they are optimized to that specific job. I hate Javascript language for many reasons(as I do in case of Java) but still believe that Javascript is better oriented towards creating client-side code for the web browsers than Java language is(when the intention is to create a web interface). Are we going to use Java idioms here or are we going to try to imitate the Javascript idioms in the Java code? How many Java libraries are supported by the GWT SDK tools? What about the unsupported libraries whose functionality is needed for the application?

    Secondly, the entire translation process is lengthy and inefficient: create an empty GWT application using the GWT SDK, fire up your favourite Java editor(eg: Eclipse) and create the Java source files in it, translate these Java files to Javascript + HTML files and finally integrate them with the rest of the server-side code(PHP, JSP etc). But there are advantages we get out of this investment as noted in the above mentioned points.

    Not all the standard Java libraries are supported by GWT. For example, only java.lang and a part of java.util are supported by the GWT tools, which means the code written using Java libraries not supported by GWT cannot be translated by the GWT tools. The developer needs to make a call whether to achieve the desired functionality by writing custom Java code or by writing the code in Javascript.(I would be tempted to go the second way as that would allow me to use the same code in other applications that don't make use of GWT).

    By the way, why don't we have the access to the GWT source code? Isn't Google a big supporter of the Free Software community?

    For developer centric GWT related discussion, go to the GWT Support Forums.
    Related Post: A Case Against Ajax Web Development Model


    If you want to receive future posts by email, enter your email address here:

    Related Posts:

  • A Case Against Ajax Web Development Model
  • Wordpress Plugin and Theme Cheatsheets
  • Google Earth For GNU/Linux
  • My Favourite Note-Taking Applications
  • Struts 2 Plugin for NetBeans IDE - nbstruts2support
  • Google Does It Again - Another Elaborate April Fool Scheme(TiSP)
  • Host Your Projects On Internet Using Google Project Hosting

  • Next Page »

    Copyright (c) 2006, 2007 Tabrez Iqbal.
    Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. Verbatim copying and distribution of this entire article is permitted in any medium without royalty provided this notice is preserved. A copy of the license is included in the section entitled "GNU Free Documentation License".


    Powered by WordPress
    This website is hosted by Dreamhost