2012年12月21日星期五

C++ Check File Exists

Check whether a file exists:


#include <sys/stat.h>
// Function: fileExists
/**
    Check if a file exists
@param[in] filename - the name of the file to check

@return    true if the file exists, else false

*/
bool fileExists(const std::string& filename)
{
    struct stat buf;
    if (stat(filename.c_str(), &buf) != -1)
    {
        return true;
    }
    return false;
}

Not sure whether it works on all platforms.

Source:StackOverFlow

C++ Split String

Making some cross-platform stuffs and shifted back to C++ recently.
Trying to do something like NSString's componentsSeparatedByString function in C++.

/* strtok example */
#include <stdio.h>
#include <string.h>

int main ()
{
  char str[] ="- This, a sample string.";
  char * pch;
  printf ("Splitting string \"%s\" into tokens:\n",str);
  pch = strtok (str," ,.-");
  while (pch != NULL)
  {
    printf ("%s\n",pch);
    pch = strtok (NULL, " ,.-");
  }
  return 0;
}


in the while loop, add those string into an array and return it back can do similiar job.

ref:cpluscplus.com