RSS

Using Vim

Learning Vim was extremely frustrating, but now I am growing to love it. Here are some useful things when learning Vim:

In Ubuntu, the default is tiny vim. To use syntax highlighting and other nice features, install the real vim:
sudo apt-get install vimGreat introduction tutorial program:
vimtutor

to exit without saving:
:q!
to save
:w
to save and exit:
:wq!
to delete lines
dd
10 dd
to delete a character
x
to undo
u
to redo
ctrl+r
to search for the word you are on
*
#
to upper case, to lower case
~
auto complete (in Insert mode)
ctrl+p
turn on C syntax highlighting
:syntax on
Usually Vim detects the language, but if not (with .cu files for example), you can set it yourself
:set syntax=c
to turn on or off line numbers
:set nu
:set nonu
to search
:/foo
to search and replace:
:%s/foo/bar/g (whole file, no confirmation)
:%s/foo/bar/gc (whole file, confirmation)
:s/foo/bar/g (single line, no confirmation)

go to beginning of file
gg
go to end of file
G
to auto-indent an entire file
gg=G
(gg gets to the beginning, = executes the indent feature with motion G, meaning to the end of the file)
For a while I stopped using Vim because I thought it couldn’t auto-format my code (automatically indent the whole file) like the good old Eclipse ctrl+shift+f, but indeed it can!

to go back to where you were before
ctrl+o
to go the other way
ctrl+i
set a bookmark called ‘a’
ma
go to the bookmark called ‘a’ (the ` is the key left of 1)
`a
center the screen on your current position
zz
select the current word
viw
select what’s inside the current set of parentheses (also works for brackets, quotes, and other stuff)
vi(
vi”
It also works with deleting, or changing
di”
ci”
also, you can include the outer quotes, parens, etc by replacing i with a:
da”
ca{

Working with multiple files:
Open a file in a new window (split horizontally)
sp filename
switch between windows
ctrl+ww
ctrl+w1w
ctrl+w2w
ctrl+w3w

Open a file in a new window (split vertically)
vs filename
Open a file in a new window (split horizontally)
sp filename
change window sizes:
make them equal size:
ctrl+w =
when split horizontally:
ctrl+w –
ctrl+w +
ctrl+w 5 +
when split vertically:
ctrl+w <>
I like to build and run my code without leaving Vim, with the following command for example:
:wa|!make emu=1 && ~/NVIDIA_CUDA_SDK/bin/linux/emurelease/fluidsGL
This command saves all open files, builds the project my calling make, and runs the binary if the build completed successfully. wa writes all open files, | adds another command, ! means to execute the following text on the command line, && means (this is Unix now, not Vim) to execute the second command if the first one completed successfully.

Vim can also do automatic indenting, set the tab size to 4, and other nice things.check this out. When I install Vim, I execute the following (explained here):
echo “syntax on
set autoindent
set smartindent
set tabstop=4
set shiftwidth=4
set showmatch
set incsearch” > ~/.vimrc

Hope this helps someone! Comments are welcome!

 
 

g++ compiler option -Weffc++

I found it quite interesting to know that g++ compiler actually provides an option (-Weffc++) which enables warnings for constructs that violate guidelines in Effective C++!!

From g++ manual (man g++)
== Begin ==
Warn about violations of the following style guidelines from Scott Meyers’ Effective C++ book:* Item 11: Define a copy constructor and an assignment operator for classes with dynamically allocated memory.
* Item 12: Prefer initialization to assignment in constructors.
* Item 14: Make destructors virtual in base classes.
* Item 15: Have “operator=” return a reference to *this.
* Item 23: Don’t try to return a reference when you must return an object.

Also warn about violations of the following style guidelines from Scott Meyers’ More Effective C++ book:

* Item 6: Distinguish between prefix and postfix forms of increment and decrement operators.
* Item 7: Never overload “&&”, “││”, or “,”.

When selecting this option, be aware that the standard library headers do not obey all of these guidelines.

== End ==

Indeed, Effective C++ is a very nice work by Scott Meyer. He has compiled two lists of top C++ publications:top 5 books and top 5 articles. His list captures right set of very well written, excellent publications in C++ as I have read most of the literature in those lists.

 
Leave a comment

Posted by on December 17, 2010 in C++ Programming

 

Factory Method and Automatic Pointers

In general when a factory method returns an instance of the created object, in C++, it is a pointer to a dynamically created memory or a resource.

Resource* factory(); // allocates dynamically

Factory method pattern does not talk about the lifetime of the object it creates. It depends upon the caller of the factory to release the resource. It can do better here. A factory method can act smarter by returing the dynamically allocated pointer by wrapping it in an automatic pointer (auto_ptr).

auto_ptr <Resource> factory(); // allocates dynamically

Returning an automatic pointer strongly indicates ownership transfer as well as
takes care of releasing the resource.

{
auto_ptr <Resource> rtemp;
rtemp = factory();
.
.
.
} // rtemp freed here automatically even in the face of exceptions!!
—–

 

 
1 Comment

Posted by on December 17, 2010 in C++ Programming

 

Using copy on STL map

Sometimes it is useful to be able iterate over all the elements of a std::map using standard algorithms like std::copy(), std::count(), std::min_element(), std::max_element(). These standard functions do not work out of the box using std::map::iterator. For example, if you want to print all the elements of a map to standard output, you can’t use the following popular copy-ostream_iterator idiom.

std::map <std::string, int> m;
std::copy (m.begin(), m.end(), std::ostream_iterator<int>(std::cout, “\n”));
// does not compile

This is because value_type of the map::iterator is a pair. In other words, if iter is a map<T,U>::iterator then *iter gives pair<T,U> and not U. If we could somehow get hold of pair::second (i.e. type U) instead of pair<T,U> all the above mentioned algorithms can be used out of the box.

The approach I took to solve this problem is to write an iterator adaptor that behaves likes any general bidirectional_iterator. In general, this approach allows map iterators to be used wherever Iterator-Pair idiom is useful. The code given below is kind of long but quite straight forward and idiomatic in nature.

#include <map>
#include <iostream>
#include <algorithm>
#include <string>
#include <list>
#include <iterator>

template <class BiDirIter>
class StdMapIteratorAdaptor
/* To make the custom iterator behave like a standard iterator by exposing
required iterator_traits */
: public
std::iterator <std::bidirectional_iterator_tag,
typename BiDirIter::value_type::second_type>
{
BiDirIter iter_;
public:

explicit StdMapIteratorAdaptor(BiDirIter const & iter = BiDirIter())
: iter_(iter) {}

bool operator == (StdMapIteratorAdaptor const & rhs) const {
return (iter_ == rhs.iter_);
}

bool operator != (StdMapIteratorAdaptor const & rhs) const {
return !(*this == rhs);
}

/* Return type is const to make it work with map::const_iterator */
typename BiDirIter::value_type::second_type const & operator * () {
return iter_->second;
}

typename BiDirIter::value_type::second_type const & operator * () const {
return iter_->second;
}

typename BiDirIter::value_type::second_type const * operator -> () const {
return &(iter_->second);
}

// Pre-increment
StdMapIteratorAdaptor & operator ++ () {
++iter_;
return *this;
}

// Post-increment
const StdMapIteratorAdaptor operator ++ (int) {
StdMapIteratorAdaptor temp (iter_);
++iter_;
return temp;
}

// Pre-decrement
StdMapIteratorAdaptor & operator — () {
–iter_;
return *this;
}

// Post-decrement
const StdMapIteratorAdaptor operator — (int) {
StdMapIteratorAdaptor temp (iter_);
–iter_;
return temp;
}
};

/* An helper function to save some typing of tedious nested C++ types
It is very similar to std::make_pair function */
template <class BiDirIter>
StdMapIteratorAdaptor <BiDirIter>
make_map_iterator_adaptor (BiDirIter const & iter)
{
return StdMapIteratorAdaptor<BiDirIter> (iter);
}

int main(void)
{
typedef std::map <std::string, int> StrIntMap;
StrIntMap months;

months[“january”] = 31;
months[“february”] = 28;
months[“march”] = 31;
months[“april”] = 30;
months[“may”] = 31;
months[“june”] = 30;
months[“july”] = 31;
months[“august”] = 31;
months[“september”] = 30;
months[“october”] = 31;
months[“november”] = 30;
months[“december”] = 31;

StrIntMap const & m = months;

StdMapIteratorAdaptor <StrIntMap::const_iterator> begin (m.begin());
StdMapIteratorAdaptor <StrIntMap::const_iterator> end (m.end());
std::copy(begin, end, std::ostream_iterator <int> (std::cout, ” “));
std::cout << std::endl;

std::list<int> l(make_map_iterator_adaptor(m.begin()),
make_map_iterator_adaptor(m.end()));

std::copy (l.begin(), l.end(), std::ostream_iterator <int> (std::cout, ” “));
std::cout << std::endl;
std::copy (make_map_iterator_adaptor(months.begin()),
make_map_iterator_adaptor(months.end()),
std::ostream_iterator <int> (std::cout, ” “));

return 0;
}

 

 
1 Comment

Posted by on December 17, 2010 in Uncategorized

 

Libcurl with C

coding libcurl in C

homepage: http://curl.haxx.se/

download: http://curl.haxx.se/download.html
latest version: latest:curl-7.21.2

libcurl: http://curl.haxx.se/libcurl/
all about libcurl with C: http://curl.haxx.se/libcurl/c/

You must include:

<curl/curl.h>

compile
gcc libcurl1.c -o libcurl1 -lcurl

important structures:

CURL *curl;
CURLcode curl_res;
CURLINFO info;

Start a libcurl easy session
curl = curl_easy_init();
see more info: http://curl.haxx.se/libcurl/c/curl_easy_init.html

set options for a curl easy handle
curl_easy_setopt(CURL *handle, CURLoption option, parameter);

CURLOPT_WRITEDATA Data pointer to pass to the file write function
curl_easy_setopt(curl, CURLOPT_WRITEDATA, tmp);
tmp: FILE handle

set proxy
curl_easy_setopt(curl, CURLOPT_PROXY, pxy);

Perform a file transfer
curl_easy_perform(CURL * handle );

End a libcurl easy session
curl_easy_cleanup(curl);

set an url
curl_easy_setopt(curl, CURLOPT_URL, url);

set file handle, where the data get writed
curl_easy_setopt(curl, CURLOPT_WRITEDATA, tmp);

download the page
curl_res = curl_easy_perform(curl);

get http status code
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code);

get size of downloaded page
curl_easy_getinfo(curl, CURLINFO_SIZE_DOWNLOAD, &c_length);

sample: libcurl1.c
##########################################

#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <fcntl.h>
#include <stdlib.h>
#include <curl/curl.h>

int main() {
  CURL *curl;
  CURLcode curl_res;
  CURLINFO info;
  long http_code;
  double c_length;  
  FILE *tmp;

  tmp=fopen("/tmp/google_index.html", "w");
  if(tmp==NULL) {
    printf("ERROR to open file /tmp/google_index.html\n");
    exit(2);
  }

  printf("init curl session\n");
  curl = curl_easy_init();
  printf("set url to download\n");
  curl_easy_setopt(curl, CURLOPT_URL, "http://www.google.de/index.html");

  printf("set file handler to write\n");
  curl_easy_setopt(curl, CURLOPT_WRITEDATA,  tmp);

  printf("download the file\n");
  curl_res = curl_easy_perform(curl);
  if(curl_res==0) {
    printf("file downloaded\n");
  } else {
    printf("ERROR in dowloading file\n");
    fclose(tmp);
    curl_easy_cleanup(curl);
  }

  printf("get http return code\n");
  curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code);
  printf("http code: %lu\n", http_code);

  printf("get size of download page\n");
  curl_easy_getinfo(curl, CURLINFO_SIZE_DOWNLOAD, &c_length);
  printf("length: %g\n", c_length);

  printf("END: close all files and sessions\n");
  fclose(tmp);
  curl_easy_cleanup(curl);

  return 0;
}

##########################################

./libcurl1
init curl session
set url to download
set file handler to write
download the file
file downloaded
get http return code
http code: 200
get size of download page
length: 6969
END: close all files and sessions

 

 
1 Comment

Posted by on December 17, 2010 in C Programming

 

Static (C++)

The static keyword can be used to declare variables, functions, class data members and class functions.

By default, an object or variable that is defined outside all blocks has static duration and external linkage. Static duration means that the object or variable is allocated when the program starts and is deallocated when the program ends. External linkage means that the name of the variable is visible from outside the file in which the variable is declared. Conversely, internal linkage means that the name is not visible outside the file in which the variable is declared.

The static keyword can be used in the following situations.

  • When you declare a variable or function at file scope (global and/or namespace scope), the static keyword specifies that the variable or function has internal linkage. When you declare a variable, the variable has static duration and the compiler initializes it to 0 unless you specify another value.
  • When you declare a variable in a function, the static keyword specifies that the variable retains its state between calls to that function.
  • When you declare a data member in a class declaration, the static keyword specifies that one copy of the member is shared by all instances of the class. A static data member must be defined at file scope. An integral data member that you declare as const staticcan have an initializer.
  • When you declare a member function in a class declaration, the static keyword specifies that the function is shared by all instances of the class. A static member function cannot access an instance member because the function does not have an implicit this pointer. To access an instance member, declare the function with a parameter that is an instance pointer or reference.
  • You cannot declare the members of a union as static. However, a globally declared anonymous union must be explicitly declared static.

Example


The following example shows how a variable declared static in a function retains its state between calls to that function.

// static1.cpp
// compile with: /EHsc
#include <iostream>

using namespace std;
void showstat( int curr ) {
   static int nStatic;    // Value of nStatic is retained
                          // between each function call
   nStatic += curr;
   cout << "nStatic is " << nStatic << endl;
}

int main() {
   for ( int i = 0; i < 5; i++ )
      showstat( i );
}
nStatic is 0
nStatic is 1
nStatic is 3
nStatic is 6
nStatic is 10

The following example shows the use of static in a class.

// static2.cpp
// compile with: /EHsc
#include <iostream>

using namespace std;
class CMyClass {
public:
   static int m_i;
};

int CMyClass::m_i = 0;
CMyClass myObject1;
CMyClass myObject2;

int main() {
   cout << myObject1.m_i << endl;
   cout << myObject2.m_i << endl;

   myObject1.m_i = 1;
   cout << myObject1.m_i << endl;
   cout << myObject2.m_i << endl;

   myObject2.m_i = 2;
   cout << myObject1.m_i << endl;
   cout << myObject2.m_i << endl;

   CMyClass::m_i = 3;
   cout << myObject1.m_i << endl;
   cout << myObject2.m_i << endl;
}
0
0
1
1
2
2
3
3

The following example shows a local variable declared static in a member function. The static variable is available to the whole program; all instances of the type share the same copy of the static variable.

Note Note
Assigning a value to a static local variable in a multithreaded application is not thread safe and we do not recommend it as a programming practice.

// static3.cpp
// compile with: /EHsc
#include <iostream>
using namespace std;
struct C {
   void Test(int value) {
      static int var = 0;
      if (var == value) 
         cout << "var == value" << endl;
      else
         cout << "var != value" << endl;

      var = value;
   }
}; 

int main() {
   C c1;
   C c2;
   c1.Test(100);
   c2.Test(100);
}
var != value
var == value

 

 
Leave a comment

Posted by on December 15, 2010 in C++ Programming

 

Returning a Class Object

There was a small controversy in the late 1980s with regard to the perceived inability of the C++ language to return a class object efficiently. Although it is more efficient to return a class object by reference or pointer rather than by value, the language does not provide any direct support for that. For example, there is no simple alternative to returning the local Matrix object by value:

Matrix operator+( const Matrix& m1, const Matrix& m2 )
{
        Matrix result;
        // do the arithmetic ...
        return result;
}

Although this revised implementation improves the operator’s performance:

// more efficient, but results in a dangling reference
Matrix& operator+( const Matrix& m1, const Matrix& m2 )
{
        Matrix result;
        // do the addition ...
        return result;
}

It also results in a dangling reference because the local object is destructed prior to the return of the function.

We can solve the problem of the dangling reference by allocating the object on the heap, such as the following:

// No way to guarantee the memory is not lost
Matrix& operator+( const Matrix& m1, const Matrix& m2 )
{
        Matrix *result = new Matrix;
        // do the addition ...
        return *result;
}

This is likely to result in memory leakage, however.

In practice, the problem is not quite as severe as it seems. The class object is not passed back by value. Rather, it is internally passed back through an additional reference parameter the compiler adds to the function. For example, the Matrix addition operator is generally transformed as follows:

// Psuedo C++ Code:
// general internal transformation of function
//     returning a class object by value

void operator+( Matrix &_retvalue,
        const Matrix &m1, const Matrix &m2)
{
    Matrix sum; 

    // invoke default constructor
    sum.Matrix::Matrix();

    // do the math

    // copy construct local sum object into _retvalue
    retvalue.Matrix::Matrix( sum );
}

The objection to this solution was based on the unnecessary invocation of the class copy constructor to initialize the additional parameter with a copy of the local class object. It would be more efficient, it was argued, if the function replaced all uses of the local class object with the parameter. The computations are applied directly to the parameter, eliminating the need both for the local class object and the copy constructor invocation. Here is the addition operator under this more aggressive transformation:

// Psuedo C++ Code:
// A more aggressive internal transformation
void operator+( Matrix &_retvalue,
        const Matrix &m1, const Matrix &m2)
{
  // replace local object with object to be returned
  // construct and do the math directly with that object

    // invoke default constructor
	_retvalue.Matrix::Matrix();

	// do the math

	// copy constructor no longer required
}

How much of a difference can that additional transformation make?  A test using the UNIX timex command to measure the performance with and without the application of the additional transformations gave:

Not Applied               : 1:48.52
Applied              :  46.73

One proposed solution was a language extension, in which the class object to hold the return value was named following the parameter list of the function:

Matrix operator+( const Matrix& m1, const Matrix& m2 )
name result   // proposed language extension
{
        // no longer write: Matrix result;
        //...
        // no longer write: return result;
}

The language extension never became part of the language, but the optimization itself has become nearly universal. It is called the name return value optimization. It is applied implicitly by a compiler when the same named object is returned from all the exit points of a function.

Because it is an optimization rather than explicitly defined within the language, however, a compiler is not required to apply it. (At the time of this writing, I am aware of only two compilers that do not provide the named return value optimization: the GNU compiler gccand Visual C++.)

To test whether your compiler applies it, run the following simple program:

class foobar {
public:
  foobar() { cout << "foobar::foobar()\n"; }
  ~foobar() { cout << "foobar::~foobar()\n"; }

  foobar( const foobar &rhs )
     { cout << "foobar::foobar( const foobar & )\n"; }

  foobar& operator=( const foobar &rhs )
     { cout << "foobar::operator=( const foobar & )\n"; }

  void ival( int nval ) { _ival = nval; }
private:
  int _ival;
};

foobar f( int val ) {
  foobar local;
  local.ival( val );
  return local;
}

int main(){
  foobar ml = f( 1024 );
  return 0;
}

If the compiler does not apply the optimization, there are two constructor calls (the construction of the local object and the copy construction of the return object) and two destructor calls as follows (this is generated by the GNU C++ compiler, gcc, running under Linux):

{me@cyanide} : g++ nrv.cpp -lstdc++ && a.out
foobar::foobar()
foobar::foobar( const foobar & )
foobar::~foobar()
foobar::~foobar()

By removing the local named object and computing the results directly within the named object, the copy constructor call and one of the destructor calls are eliminated. For example, here is the output of the same program with the optimization applied (this is generated by the KAI C++ compiler running under Linux):

{stan@andromeda} : KCC nrv.cc && a.out
foobar::foobar()
foobar::~foobar()

So, what if your compiler does not apply the name return value optimization? An alternative programming idiom is to provide a “computational constructor” that does the work previously done in the actual function, and to return that within the function. Here’s a simple example using our foobar class:

class foobar {
public:
  // simple example of computational constructor ...
    foobar( int val ) : _ival( val )
     { cout << "foobar::foobar( " << val << " )\n"; }
  // ...
};

/* previous version using local object and 'computation'
foobar f( int val ) {
  foobar local;
  local.ival( val );
  return local;
}
*/

// revised version invoking the 'computational' constructor
foobar f( int val ) { return foobar( 1024 ); }

In effect, we’ve hand-optimized the function: the local object is removed, and the computation is applied directly to the constructed object. The compiler completes the optimization by applying the constructor to the class reference parameter introduced to hold the result:

// C++ Pseudo Code:
// internal transformation of our hand-optimized function
void f( foobar & _result, int val )
{ _result.foobar::foobar( 1024 ); }

When compiled and executed, our revised program mimics the result of having the name return value optimization applied:

foobar::foobar( 1024 )
foobar::~foobar()
 
3 Comments

Posted by on December 13, 2010 in Uncategorized

 

Using Smart Pointers in C++

This article gives an overview of a bunch of smart pointer classes for C++. Some of the facilities discussed are non-standard, but part of widely used libraries. First let us define a class that will serve as the base of all our code examples. The class is called FileReader. It wraps up the low-level details of opening and reading a text file. The constructor of the class is passed the name of a file. The file is opened and its handle is stored in a private member file_ of type FILE. The destructor will close the FILE handle, thereby preventing any scope for resource leaks. The user can call the read(string&) function to get the contents of the file.

class FileReader
{
public:
  FileReader () : file_name_(""), file_(NULL)
  { }

  FileReader (const std::string &file_name)
    : file_name_(file_name), file_(NULL)
  {
    file_ = fopen (file_name_.c_str(), "r");
    if (file_ == NULL)
      throw std::string ("file_open_failed");
  }

  ~FileReader ()
  {
    if (file_ != NULL)
      {
        fclose (file_);
        file_ = NULL;
      }
  }

  void read (std::string &data)
  {
    if (file_ == NULL)
      return;
    size_t sz = get_file_size ();
    char *buffer = new char [sz + 1];
    fread (buffer, sizeof (char), sz, file_);
    buffer[sz] = '';
    data.assign (buffer);
    delete[] buffer;
  }

private:
  size_t get_file_size ()
  {
    fseek (file_, 0L, SEEK_END);
    size_t sz = ftell (file_);
    fseek (file_, 0L, SEEK_SET);
    return sz;
  }

  std::string file_name_;
  FILE *file_;
};

This class makes use of RAII and takes care of its own memory management:

void test (const std::string &fileName)
{
    FileReader fileReader (fileName);
    std::string contents;
    fileReader.read (contents);
} // The destructor is called and the file_ handle
  // is released at the end of scope.

If we create FileReader objects dynamically, then we have to explicitly call delete to execute the destructor:

void test (const std::string &fileName)
{
    FileReader *fileReader = new FileReader
                                  (fileName);
    std::string contents;
    fileReader->read (contents);
    delete fileReader;
}

Standard C++ gives us auto_ptr, a smart pointer facility which takes ownership of a dynamic object and cleans it up automatically when the auto_ptr goes out of scope. We can re-write our test function to useauto_ptr:

#include <memory> // for auto_ptr.

void test (const std::string &fileName)
{
    std::auto_ptr<FileReader> fileReader (new
                               FileReader (fileName));
    std::string contents;
    fileReader->read (contents);
} // FileReader pointer is destroyed by auto_ptr.

auto_ptr has one associated danger that we need to be aware of. One pointer can be owned only by a single auto_ptr at a time. So when we copy an auto_ptr the ownership is transfered to the destinationauto_ptr and the pointer in the source auto_ptr is set to NULL. This is required to avoid releasing the wrapped-up pointer more than once. Thus the call to read() in the following function will lead to unspecified behavior:

void test (const std::string &fileName)
{
    std::auto_ptr<FileReader> fileReader (new
                           FileReader (fileName));
    std::string contents;
    std::auto_ptr<FileReader> tmp = fileReader;
    // Unspecified behavior, probably a crash!
    fileReader->read (contents);
} 

The Boost library provide an auto_ptr replacement that don’t have this problem. This class is calledscoped_ptr. A scoped_ptr is noncopyable and prevents shared ownership of a pointer. The attempt to make a copy of a scoped_ptr will result in a compile-time error:

#include <boost/scoped_ptr.hpp>

void test (const std::string &fileName)
{
    boost::scoped_ptr<FileReader> fileReader (
                             new FileReader (fileName));
    // Compile time error.
    std::string contents;
    boost::scoped_ptr<FileReader> tmp = fileReader;
    fileReader->read (contents);
}

This prevents scoped_ptr objects from being used in containers like std::vector as they need to make copies of the object. If you want a smart pointer that is copyable, use a shared_ptr. It uses reference counting and memory is reclaimed when the last shared_ptr holding a reference to it goes out of scope.shared_ptr also provide comparison operators so that it can work with the standard associative containers.

#include <boost/shared_ptr.hpp>

void test (const std::string &fileName)
{
    boost::scoped_ptr<FileReader> copy;
    {
       boost::scoped_ptr<FileReader> fileReader (
                                  new FileReader (fileName));
       std::string contents;
       tmp = fileReader;
       fileReader->read (contents);
    } // The FileReader object will not be reclaimed
      // here as copy holds a reference to it.
} // The FileReader object is reclaimed when copy goes
  // out of scope.

Neither scoped_ptr nor shared_ptr can manage arrays as they use delete to release the pointer. Usescoped_array or shared_array, which make use of delete[] for that purpose. The following sample shows allocating an array of integers using scoped_array:

void test ()
{
  size_t count = 10;
  boost::scoped_array<int> squares (new int[count]);
  for (size_t i = 0; i < count; ++i)
    {
      squares[i] = i * i;
    }
  for (size_t i = 0; i < count; ++i)
    {
      std::cout squares [i] ' ';
      // => 0 1 4 9 16 25 36 49 64 81
    }
}
 
Leave a comment

Posted by on December 13, 2010 in C++ Programming

 

C++ Friend Functions

In this C++ tutorials, you will learn about friend functions, need for friend function, how to define and use friend function and few important points regarding friend function, explained with example.

Need for Friend Function:

When a data is declared as private inside a class, then it is not accessible from outside the class. A function that is not a member or an external class will not be able to access the private data. A programmer may have a situation where he or she would need to access private data from non-member functions and external classes. For handling such cases, the concept of Friend functions is a useful tool.

What is a Friend Function?

A friend function is used for accessing the non-public members of a class. A class can allow non-member functions and other classes to access its own private data, by making them friends. Thus, a friend function is an ordinary function or a member of another class.

How to define and use Friend Function in C++:

The friend function is written as any other normal function, except the function declaration of these functions is preceded with the keyword friend. The friend function must have the class to which it is declared as friend passed to it in argument.

Some important points to note while using friend functions in C++:

  • The keyword friend is placed only in the function declaration of the friend function and not in the function definition. .
  • It is possible to declare a function as friend in any number of classes. .
  • When a class is declared as a friend, the friend class has access to the private data of the class that made this a friend. .
  • A friend function, even though it is not a member function, would have the rights to access the private members of the class. .
  • It is possible to declare the friend function as either private or public. .
  • The function can be invoked without the use of an object. The friend function has its argument as objects, seen in example below.

Example to understand the friend function:

#include 
class exforsys
{
private:
int a,b;
public:
void test()
{
a=100;
b=200;
}
friend int compute(exforsys e1)

//Friend Function Declaration with keyword friend and with the object of class exforsys to which it is friend passed to it };

int compute(exforsys e1)
{
//Friend Function Definition which has access to private data
return int(e1.a+e2.b)-5;
}

main()
{
exforsys e;
e.test();
cout<<“The result is:”<
//Calling of Friend Function with object as argument.

}

The output of the above program is

The result is:295

The function compute() is a non-member function of the class exforsys. In order to make this function have access to the private data a and b of class exforsys , it is created as a friend function for the class exforsys. As a first step, the function compute() is declared as friend in the class exforsys as:

friend int compute (exforsys e1)

The keyword friend is placed before the function. The function definition is written as a normal function and thus, the function has access to the private data a and b of the class exforsys. It is declared as friend inside the class, the private data values a and b are added, 5 is subtracted from the result, giving 295 as the result. This is returned by the function and thus the output is displayed as shown above.

 
4 Comments

Posted by on December 8, 2010 in C++ Programming

 

MySQL C API

MySQL C API programming tutorial

About this tutorial

This is a C programming tutorial for the MySQL database. It covers the basics of MySQL programming with the C API.

About MySQL database

MySQL logo

MySQL is a leading open source database management system. It is a multi user, multithreaded database management system. MySQL is especially popular on the web. It is a one of the parts of the very popular LAMPplatform. Linux, Apache, MySQL, PHP. MySQL is owned by a swedish company called MySQL AB. This company and Trolltech are prominent open source companies. MySQL database is available on most important OS platforms. It runs under BSD Unix, Linux, Windows or Mac. Wikipedia and YouTube use MySQL. These sites manage millions of queries each day. MySQL comes in two versions. MySQL server system and MySQL embedded system.

First example

Our first example will test one MySQL function call.

#include <my_global.h>
#include <mysql.h>

int main(int argc, char **argv)
{
  printf("MySQL client version: %s\n", mysql_get_client_info());
}

The mysql_get_client_info() shows the MySQL client version.

gcc version.c -o version  `mysql_config --cflags --libs`

Here is how we compile the code example.

 $ ./version
 MySQL client version: 5.0.38

 #include <my_global.h>
 #include <mysql.h>

We include necessary header files. mysql.h is the most important header file for MySQL function calls.my_global.h includes some global declarations a functions. Among other thing, it includes the standard input/output header file.

 printf("MySQL client version: %s\n", mysql_get_client_info());

This code line outputs the version of the MySQL client. For this, we use the mysql_get_client_info() function call.

Creating a database

The next code example will create a database.

#include <my_global.h>
#include <mysql.h>

int main(int argc, char **argv)
{

  MYSQL *conn;

  conn = mysql_init(NULL);

  if (conn == NULL) {
      printf("Error %u: %s\n", mysql_errno(conn), mysql_error(conn));
      exit(1);
  }

  if (mysql_real_connect(conn, "localhost", "prasanth", "passwd", NULL, 0, NULL, 0) == NULL) {
      printf("Error %u: %s\n", mysql_errno(conn), mysql_error(conn));
      exit(1);
  }

  if (mysql_query(conn, "create database testdb")) {
      printf("Error %u: %s\n", mysql_errno(conn), mysql_error(conn));
      exit(1);
  }

  mysql_close(conn);

}

The code example connects to the MySQL database system and creates a new database called testdb.

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| testdb             |
+--------------------+
3 rows in set (0.00 sec)

This is the proof, that the database was created.

We include error checking in this example. It is important to check for possible errors. Database programming is a field, where many things might go wrong. For clarity reasons, later examples will be without error checking. I suppose that it is clear for everyone, that it is every programmers responsibility to do error checking.

The code example can be divided into these parts.

  • Initiation of a connection handle structure
  • Creation of a connection
  • Execution of a query
  • Closing of the connection
 MYSQL *conn;

We declare a pointer to a MYSQL structure. This structure will serve as a connection handler.

 conn = mysql_init(NULL);

The mysql_init() function obtains a connection handler.

 if (conn == NULL) {
     printf("Error %u: %s\n", mysql_errno(conn), mysql_error(conn));
     exit(1);
 }

We check the return value. If the mysql_init() function fails, we print the error message and terminate the application.

 if (mysql_real_connect(conn, "localhost", "prasanth", "passwd", NULL, 0, NULL, 0) == NULL) {
     printf("Error %u: %s\n", mysql_errno(conn), mysql_error(conn));
     exit(1);
 }

The mysql_real_connect() function establishes a connection to the database. We provide connection handler, host name, user name and passwor parameters to the function. The other four parameters are the database name, port number, unix socket and finally the client flag.

 if (mysql_query(conn, "create database testdb")) {
     printf("Error %u: %s\n", mysql_errno(conn), mysql_error(conn));
     exit(1);
 }

The mysql_query() executes the SQL statement. In our case, the statement creates a new database.

 mysql_close(conn);

Finally, we close the database connection.

Creating and populating a table

The next code example will create a table and insert some data into it.

#include <my_global.h>
#include <mysql.h>

int main(int argc, char **argv)
{

  MYSQL *conn;

  conn = mysql_init(NULL);
  mysql_real_connect(conn, "localhost", "prasanth", "passwd", "testdb", 0, NULL, 0);

  mysql_query(conn, "CREATE TABLE writers(name VARCHAR(25))");

  mysql_query(conn, "INSERT INTO writers VALUES('Leo Tolstoy')");
  mysql_query(conn, "INSERT INTO writers VALUES('Jack London')");
  mysql_query(conn, "INSERT INTO writers VALUES('Honore de Balzac')");
  mysql_query(conn, "INSERT INTO writers VALUES('Lion Feuchtwanger')");
  mysql_query(conn, "INSERT INTO writers VALUES('Emile Zola')");

  mysql_close(conn);

}

We don’t use any new MySQL function call here. We use mysql_query() function call to both create a table and insert data into it.

 mysql_real_connect(conn, "localhost", "prasanth", "passwd", "testdb", 0, NULL, 0);

We connect to testdb database. The user name is prasanth and password is passwd.

 mysql_query(conn, "CREATE TABLE writers(name VARCHAR(25))");

Here we create a table named writers. It has one varchar column.

 mysql_query(conn, "INSERT INTO writers VALUES('Leo Tolstoy')");

We insert one writer name into the writers table.

mysql> show tables;
+------------------+
| Tables_in_testdb |
+------------------+
| writers          |
+------------------+
1 row in set (0.00 sec)

We show tables in the database.

mysql> select * from writers;
+-------------------+
| name              |
+-------------------+
| Leo Tolstoy       |
| Jack London       |
| Honore de Balzac  |
| Lion Feuchtwanger |
| Emile Zola        |
+-------------------+
5 rows in set (0.00 sec)

We select all data from the table.

Retrieving data from the database

In the next example, we will retrieva data from a table.

Steps:

  • Create a connection
  • Execute query
  • Get the result set
  • Fetch all available rows
  • Free the result set
#include <my_global.h>
#include <mysql.h>

int main(int argc, char **argv)
{

  MYSQL *conn;
  MYSQL_RES *result;
  MYSQL_ROW row;
  int num_fields;
  int i;

  conn = mysql_init(NULL);
  mysql_real_connect(conn, "localhost", "prasanth", "passwd", "testdb", 0, NULL, 0);

  mysql_query(conn, "SELECT * FROM writers");
  result = mysql_store_result(conn);

  num_fields = mysql_num_fields(result);

  while ((row = mysql_fetch_row(result)))
  {
      for(i = 0; i < num_fields; i++)
      {
          printf("%s ", row[i] ? row[i] : "NULL");
      }
      printf("\n");
  }

  mysql_free_result(result);
  mysql_close(conn);

}

The example prints all names from the writers table.

$ ./select
Leo Tolstoy
Jack London
Honore de Balzac
Lion Feuchtwanger
Emile Zola

 mysql_query(conn, "SELECT * FROM writers");

We execute the query, that will retrieve all names from the writers database.

 result = mysql_store_result(conn);

We get the result set.

 num_fields = mysql_num_fields(result);

We get the number of fields in the table.

 while ((row = mysql_fetch_row(result)))
 {
     for(i = 0; i < num_fields; i++)
     {
         printf("%s ", row[i] ? row[i] : "NULL");
     }
     printf("\n");
 }

We fetch the rows and print them to the screen.

 mysql_free_result(result);

We free the resources.

Column headers

In the next example, we will retrieve data and show the their column names from the table.

For this, we will create a new table friends.

 mysql> create table friends (id int not null primary key auto_increment,
                               name varchar(20), age int);

 mysql> insert into friends(name, age) values('Tom', 25);
 mysql> insert into friends(name, age) values('Elisabeth', 32);
 mysql> insert into friends(name, age) values('Jane', 22);
 mysql> insert into friends(name, age) values('Luke', 28);

We insert some data into the table.

#include <my_global.h>
#include <mysql.h>

int main(int argc, char **argv)
{

  MYSQL *conn;
  MYSQL_RES *result;
  MYSQL_ROW row;
  MYSQL_FIELD *field;

  int num_fields;
  int i;

  conn = mysql_init(NULL);
  mysql_real_connect(conn, "localhost", "prasanth", "passwd", "testdb", 0, NULL, 0);

  mysql_query(conn, "SELECT * FROM friends");
  result = mysql_store_result(conn);

  num_fields = mysql_num_fields(result);

  while ((row = mysql_fetch_row(result)))
  {
      for(i = 0; i < num_fields; i++)
      {
          if (i == 0) {
             while(field = mysql_fetch_field(result)) {
                printf("%s ", field->name);
             }
          printf("\n");
          }
          printf("%s  ", row[i] ? row[i] : "NULL");
      }
  }
  printf("\n");

  mysql_free_result(result);
  mysql_close(conn);
}

The example is similar to the previous one. It just adds column header names to it.

 while(field = mysql_fetch_field(result)) {
     printf("%s ", field->name);
 }

The mysql_fetch_field() call returns a MYSQL_FIELD structure. We get the column header names from this structure.

$ ./headers
id name age
1  Tom  25
2  Elisabeth  32
3  Jane  22
4  Luke  28

And this is the output of our program.

Inserting images into MySQL database

Some people prefer to put their images into the database, some prefer to keep them on the file system for their applications. Technical difficulties arise when we work with millions of images. Images are binary data. MySQL database has a special data type to store binary data called BLOB (Binary Large Object).

mysql> describe images;
+-------+------------+------+-----+---------+-------+
| Field | Type       | Null | Key | Default | Extra |
+-------+------------+------+-----+---------+-------+
| id    | int(11)    | NO   | PRI |         |       |
| data  | mediumblob | YES  |     | NULL    |       |
+-------+------------+------+-----+---------+-------+
2 rows in set (0.00 sec)

This is the table, that we will use in our example. It can be created by the following SQL statement.

create table images(id int not null primary key, data mediumblob);

#include <my_global.h>
#include <mysql.h>

int main(int argc, char **argv)
{
  MYSQL *conn;

  int len, size;
  char data[1000*1024];
  char chunk[2*1000*1024+1];
  char query[1024*5000];

  FILE *fp;

  conn = mysql_init(NULL);
  mysql_real_connect(conn, "localhost", "prasanth", "passwd", "testdb", 0, NULL, 0);

  fp = fopen("image.png", "rb");
  size = fread(data, 1, 1024*1000, fp);

  mysql_real_escape_string(conn, chunk, data, size);

  char *stat = "INSERT INTO images(id, data) VALUES('1', '%s')";
  len = snprintf(query, sizeof(stat)+sizeof(chunk) , stat, chunk);

  mysql_real_query(conn, query, len);

  fclose(fp);
  mysql_close(conn);
}

In this example, we will insert one image into the images table. The image can be max 1 MB.

 fp = fopen("image.png", "rb");
 size = fread(data, 1, 1024*1000, fp);

Here we open the image and read it into the data array.

 mysql_real_escape_string(conn, chunk, data, size);

Binary data can obtain special characters, that might cause troubles in the statements. We must escape them. The mysql_real_escape_string() puts the encoded data into the chunk array. In theory, every character might be a special character. That’s why the chunk array two times as big as the data array. The function also adds a terminating null character.

 char *stat = "INSERT INTO images(id, data) VALUES('1', '%s')";
 len = snprintf(query, sizeof(stat)+sizeof(chunk) , stat, chunk);

These two code lines prepare the MySQL query.

 mysql_real_query(conn, query, len);

Finally, we execute the query.

Selecting images from MySQL database

In the previous example, we have inserted an image into the database. In the following example, we will select the inserted image back from the database.

#include <my_global.h>
#include <mysql.h>

int main(int argc, char **argv)
{
  MYSQL *conn;
  MYSQL_RES *result;
  MYSQL_ROW row;

  unsigned long *lengths;
  FILE *fp;

  conn = mysql_init(NULL);
  mysql_real_connect(conn, "localhost", "prasanth", "passwd", "testdb", 0, NULL, 0);
  fp = fopen("image.png", "wb");
  mysql_query(conn, "SELECT data FROM images WHERE id=1");
  result = mysql_store_result(conn); 
  row = mysql_fetch_row(result); 
  lengths = mysql_fetch_lengths(result);  
  fwrite(row[0], lengths[0], 1, fp); 
  mysql_free_result(result); 
  fclose(fp); 
  mysql_close(conn); 
}

In this example, we will create an image file from the database.

 fp = fopen("image.png", "wb");

We open a file for writing.

 mysql_query(conn, "SELECT data FROM images WHERE id=1");

We select an image with id 1.

 row = mysql_fetch_row(result);

The row contains raw data.

 lengths = mysql_fetch_lengths(result);

We get the length of the image.

 fwrite(row[0], lengths[0], 1, fp);

We create the image file using the fwrite() standard function call.

 
Leave a comment

Posted by on December 7, 2010 in C Programming