Tuesday, 29 March 2011

Reading file names from directory

The other day I had to read all the file names from a directory and I found it really difficult to write a simple program to do that. While searching I ended up at Stack Overflow and the following example is taken from here.

Note that the 'dirent.h' is not available as standard windows file and the best option is to download it from here and add it in your include directory of the project.

The program as follows:


//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
#include<iostream>

#pragma warning( disable : 4996 )
#include "dirent.h"
#pragma warning( default : 4996 )

using namespace
std;

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

if
(argc != 2)
{

cout<<"Usage: "<<argv[0]<<" <Directory name>"<<endl;
return
-1;
}


DIR *dir;
dir = opendir (argv[1]);
if
(dir != NULL)
{

cout<<"Directory Listing for "<<argv[1]<<" : "<<endl;
struct
dirent *ent;
while
((ent = readdir (dir)) != NULL)
{

cout<<ent->d_name<<endl;
}
}

else

{

cout<<"Invalid Directory name"<<endl;
return
-1;
}


return
0;
}

Note that in this program we put Command-line arguments argc and argv. What this means is that the final .exe is run using command prompt and the first parameter will be exe file name and the second parameter will be the directory path or you can add the directory path in Debugging->Command arguments of the properties

You may also encounter the following warning

warning C4996: 'strcpy': This function or variable may be unsafe. Consider using strcpy_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.

to get rid of it, I have used the #Pragma supressor.

You may also get the following error:

error C2664: 'FindFirstFileW' : cannot convert parameter 1 from 'char *' to 'LPCWSTR'
to get rid of it, go to properties->general->Character set - default is 'Use Unicode Charachter set', change it to 'Use Multi-Byte Character Set'

The output is as follows:

Tuesday, 22 March 2011

Reading Files into Vector

Thought of this while trying to create a parser. The intention is to read a complete text file into a vector and then use this vector for other operations. This program shows how to read from a text file into vectors.

The input file is as follows:

Line num 1

Another line

Line number 3

4th Line!

**%** Last line **%**

Program as follows:



//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
#include <iostream>
#include <vector>
#include <fstream>
#include <string>

using namespace
std;

int
main()
{

vector<std::string> lines;
lines.reserve(5000); //Assuming that the file to read can have max 5K lines

string fileName("test.txt");

ifstream file;
file.open(fileName.c_str());

if
(!file.is_open())
{

cerr<<"Error opening file : "<<fileName.c_str()<<endl;
return
-1;
}


//Read the lines and store it in the vector
string line;
while
(getline(file,line))
{

lines.push_back(line);
}


file.close();

//Dump all the lines in output
for(unsigned int i = 0; i < lines.size(); i++)
{

cout<<i<<". "<<lines[i]<<endl;
}


return
0;
}




Output as follows:

Tuesday, 8 March 2011

Switch Case using string

When I started thinking of this example, I also faced some of the other problems that I have encountered in my initial days of C++. One of these problems was how to convert String to multiple Ints and how to split strings easily, etc. Hopefully you will find the example useful.



//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
#include<iostream>
#include<string>
#include<sstream>
#include<map>

using namespace
std;

void
split(const string& input, int& num1, int& num2, string& operation);
int
calculate(int num1, int num2, string operation);

int
main()
{

string s[5] = {"2 + 2", "4 - 1", "4 * 6", "18 / 3", "12 ^ 2"};

for
(int i = 0; i < 5 ; i++)
{

int
num1=0, num2=0;
string op;
split(s[i], num1, num2, op);
int
retVal = calculate(num1, num2, op);
cout<<s[i]<<" = "<<retVal<<endl;
}


return
0;
}


void
split(const string& input, int& num1, int& num2, string& operation)
{

istringstream iss(input);
iss >> num1;
iss >> operation;
iss >> num2;
}


int
calculate(int num1, int num2, string operation)
{

enum
Operators {unknown, add, sub, mul, div};
map<string, Operators> mapOfOperators;
mapOfOperators["+"] = add;
mapOfOperators["-"] = sub;
mapOfOperators["*"] = mul;
mapOfOperators["/"] = div;

switch
(mapOfOperators[operation])
{

case
add:
return
num1 + num2;
case
sub:
return
num1 - num2;
case
mul:
return
num1 * num2;
case
div:
return
num1 / num2;
default
:
cout<<"Unrecognised Operator "<<operation<<endl;
}

return
0;
}


The output is as follows:
See Also: Codeguru article on 'Switch on Strings in C++'.

Friday, 4 March 2011

Removing all white-spaces from a string

Continuing on the same theme as the last post. What if all the spaces need to be stripped out from the input string:



//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
#include<iostream>
#include<string>

using namespace
std;

string removeAllSpaces(const string& s)
{

string newStr(s);
bool
spacesLeft = true;

while
(spacesLeft)
{

int
pos = newStr.find(" ");
if
(pos != string::npos)
{

newStr.erase(pos, 1);
}

else

spacesLeft = false;
}


return
newStr;
}


int
main()
{

string aString("This string has multiple spaces problem!");

cout<<"Original : "<<aString<<endl;
cout<<"Modified : "<<removeAllSpaces(aString)<<endl;

return
0;
}





The output is as follows:

Tuesday, 1 March 2011

Removing Multiple White-spaces from a string

A simple program to remove an arbitrary number of white spaces in between words. Program as follows:




//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
#include<iostream>
#include<string>

using namespace
std;

bool
removeDoubleSpaces(string& s)
{

bool
found = true;

int
i = s.find(" "); //Search for 2 spaces
if(i != string::npos)
{

s.replace(i, 2, " ");
}

else

found = false;

return
found;
}


string removeMultipleSpaces(const string& s)
{

string newStr(s);
bool
found = true;

while
(found)
{

found = removeDoubleSpaces(newStr);
}


return
newStr;
}


int
main()
{

string aString("This string has multiple spaces problem!");

cout<<"Original : "<<aString<<endl;
cout<<"Modified : "<<removeMultipleSpaces(aString)<<endl;

return
0;
}




The output is as follows: