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 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

  • 10 Comments »

    1. I need to know how to get started on writing a program that uses enumeration with three paramters (Iosceles, noTriangle, something else I forgot) but when do I use int main () and how to do a loop to get the output of the triangle to print out?

      Quote

      Comment by TaSharon — November 2, 2006 @ 10:10 pm

    2. There is some mistakes in your code: the order of choice 2 and choice 3.

      2. Remove File\n3. Rename File

      case '2':
      std::cout>name;
      std::cout>new_name;
      bfs::rename(name, new_name);
      break;
      case '3':
      std::cout>name;
      bfs::remove(bfs::path(name));
      break;

      Quote

      Comment by Yanling Zhi — May 12, 2007 @ 10:22 am

    3. Thanks for the correction, I have updated the post.

      Quote

      Comment by tabrez — May 12, 2007 @ 5:22 pm

    4. How can you delete a directory, I'm getting errors when i try to use "remove(path_to_dir)", I'll also tried "path_to_dir.remove_leaf()".

      Quote

      Comment by brad — July 3, 2007 @ 12:50 pm

    5. I got it to work if you use remove_all('path_to_dir'), is that the only/best way to go about it?

      Quote

      Comment by brad — July 4, 2007 @ 2:42 am

    6. hello every one ,
      can any one please help me where to get tutorials of boost filesystem ???
      i wan't able to get it naywhere
      mohan gupta

      Quote

      Comment by mohan gupta — April 23, 2008 @ 4:52 pm

    7. Mohan Gupta,
      1. I have made three blog posts about Boost Filesystem library:
      Writing Portable C++ Programs to Acess The Filesystem
      C++ Boost Filesystem Library(Part II): Example Programs
      C++ Boost Filesystem Library(Part III): Example Programs

      2. Boost Filesystem official documentation is informative and easy to follow:
      Boost Filesystem Library

      3. The following book covers many useful Boost libraries, including Boost Filesystem library:
      Beyond the C++ Standard Library: An Introduction to Boost

      Quote

      Comment by tabrez — April 25, 2008 @ 1:26 pm

    8. Hi,
      i am new to the Boost library. I was trying to check if a directory exists in a path and if it doesnt exits, the directory needs to be created. Tried the program as given above, but I am encountering compilation problems. I need help

      My code:

      #include<iostream>
      #include<boost/filesystem>

      using namespace std;
      namespace bfs=boost::filesystem;

      int main()
      {
      bfs::path p("/home/mnadig/ANj");
      bfs::create_directory(p);
      std::cout<<"Operation finished."<<std::endl;
      return 0;
      }

      Error:
      /vobs/src9005/SS_TestSNMP/src/SNMP_Delivery/myExample/dir/dir.cpp:16: undefined reference to `boost::filesystem::path::path(char const*)'
      dir.o(.text+0x173):/vobs/src9005/SS_TestSNMP/src/SNMP_Delivery/myExample/dir/dir.cpp:17: undefined reference to `boost::filesystem::create_directory(boost::filesystem::path const&)'

      Quote

      Comment by Anjali — May 9, 2008 @ 5:14 pm

    9. #include<iostream>
      #include<boost/filesystem>

      using namespace std;
      namespace bfs=boost::filesystem;

      int main()
      {
      bfs::path p("/home/mnadig/ANj");
      bfs::create_directory(p);
      std::cout<<"Operation finished."<<std::endl;
      return 0;
      }

      Sorry the header files were not displayed when i pasted it. Here it is again

      Quote

      Comment by Anjali — May 9, 2008 @ 5:16 pm

    10. You need to install the Boost library properly; in this case, you need to build the Boost Filesystem library(or install the lib package for your OS/distribution). You then need to link to that library when building your application. See the Boost installation posts on the following page for more help:

      http://beans.seartipy.com/category/c_boost/

      Quote

      Comment by tabrez — May 11, 2008 @ 2:04 pm

    RSS feed for comments on this post. TrackBack URI

    Leave a comment

    Subscribe without commenting


    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