Sunday, March 21, 2010

C++: Managing I/O streams

Managing I/O streams

Now in this chapter, we shall read about the following concepts:
  • few useful functions
  • other ways to open a file
  • cross checking the fstream variable
  • read from & write to file simultaneously
So lets have fun of reading...

So far we saw only one way of opening the file as per the following syntax.
ifstream file("filename.txt");

Well, this is not the only way! As mentioned before, the above code creates an object from class ifstream, and passes the name of the file to be opened to its constructor. But in fact, there are several overloaded constructors, which can take more than one parameter. Also, there is function open() that can do the same job. Here is an example of the above code, but using the open() function:

ifstream file;
file.open("filename.txt");


What is the difference you ask? Well, there is no difference! Just if you want to create a file handle, but don’t want to specify the file name immediately, you can specify it later with the function open(). And by the way, other use of open() is for example if you open a file, then close it, and using the same file handle open another file. This way, you will need the open() function.

Consider the following code example:

#include


void read (ifstream &T)
{
 char ch;
 while(!T.eof())
 {
 T.get(ch);
 cout << ch;
 }
 cout << endl << "---" << endl;
}

void main()
{
ifstream T("filename1.txt");
read(T);
T.close();
T.open("filename2.txt");
read(T);
T.close();
}

So, as long as filename1.txt and filename2.txt exists and has some text into, you will see it!
Now, it’s time to show you that the file name is not the only parameter that you can pass to the open() function or the constructor (it’s the same). Here is a prototype:
ifstream file(char *filename, int open_mode);

You should know that filename is the name of the file (a string). The new content here is the open mode. The value of open_mode defines how to be opened the file. Here is a table of the open modes:
NameDescription
ios::inOpen file to read
ios::outOpen file to write
ios::appAll the date you write, is put at the end of the file. It calls ios::out
ios::ateAll the date you write, is put at the end of the file. It does not call ios::out
ios::truncDeletes all previous content in the file. (empties the file)
ios::nocreateIf the file does not exists, opening it with the open() function gets impossible.
ios::noreplaceIf the file exists, trying to open it with the open() function, returns an error.
ios::binaryOpens the file in binary mode.

In fact, all these values are int constants from an enumerated type. But for making your life easier, you can use them as you see them in the table.


Here is an example on how to use the open modes:

#include

void main()
{
ofstream file("filename1.txt", ios::ate);
file << "Write at end of file\n";
file.close();
}

As you see in the table, using ios::ate will write at the end of the file. If we didn’t use it, the file will be overwritten, but because of it, we can just add text to it. So, if filename1.txt has this text:

Hi! Good morning!

Running the above code, will add “That’s new!” to it, so it will look this way:

Hi! Good morning!Write at end of file
If you want to set more than one open mode, just use the OR operator as follows:
ios::ate | ios::binary

Now, it’s time to read something really useful! Till now we saw how to read from or write to file, but not done using same fstream handler. Now let us see how it works:

fstream file("filename.txt", ios::in | ios::out);

In fact, that is only the declaration. I will show you a code example, just several lines bellow. But I first want to mention some things you should know.

The code line above, creates a file stream handle, named “file”. As you know, this is an object from class fstream. When using fstream, you should specify ios::in and ios::out as open modes. This way, you can read from the file, and write in it, in the same time, without creating new file handles. Well, of course, you can only read or write. Then you should use either ios::in either ios::out, but if you are going to do it this way, why don’t you do it either with ifstream, either with ofstream?

Here is the code example:

#include

void main()
{
fstream File("filename.txt",ios::in | ios::out);
file << "Hi!"; //put "Hi!" in the file;
static char str[10];
file.seekg(ios::beg); //get back to the beginning of the file //this function is explained a bit later
file >> str;
cout << str << endl;
file.close();
}

Let me explain line by line bcause of many new things.

fstream File("filename.txt", ios::in | ios::out); - This line, creates an object from class fstream. At the time of execution, the program opens the file test.txt in read/write mode. This means, that you can read from the file, and put data into it, at the same time.

file << "Hi!"; - We already know this.

static char str[10]; - This makes a char array with 10 cells. Since static may be unfamiliar to you. If so- ignore it. It just initializes the array when at the time of creation.

file.seekg(ios::beg); - This line makes the pointer that is responsiable of reading and writing the text to the begining of the file.
while(!OpenFile.eof())

{

file.get(ch);
cout << ch;

}

This is a while loop, that will loop until you reach the end of the file. But how do the loop know if the end of the file is reached? Well, when you read the file, there is something like an inside-pointer, that shows where you are up to, with the reading (and writing, too). It is like the cursor in Notepad. And every time you call file.get(ch) it returns the current character to the ch variable, and moves the inside-pointer one character after that, so that the next time this function is called, it will return the next character. And this repeats, until you reach the end of the file.

Now the function seekg() will put the inside-pointer to a specific place (specified by you). You can use:

ios::beg - to put it in the beginning of the file
ios::end - to put it at the end of the file

Or you can also set the number of characters to go back or after. For example, if you want to go 5 characters back, you should write:
file.seekg(-5);

If you want to go 40 character after, just write:
file.seekg(40);

I also have to mention, that the seekg() function is overloaded, and it can take two parameters, too. The other version is this one:

file.seekg(-5,ios::end);

In this example, you will be able to read the last 4 characters of the text, because:

1) You go to the end (ios::end)
2) You go 5 characters before the end (-5)

Why you will read 4 but not 5 characters? Well, just assume that one is lost, because the last thing in the file is not a character nor white space. It is just position.

file >> str; - That’s new, too! Well, I believe this line reminds you of cin >> . I fact, it has much to do with it. This line reads one word from the file, and puts it into the specified array.

For example, if the file has this text:

Hi! How are you?

Using file >> str, will put just “Hi!” to the str array. You should have noticed, that it actually reads until it meets a white space.

And as what I put in the file was “Hi!” I don’t need to do a while loop, that takes more time to code. That’s why I used this way. By the way, in the while loop for reading, that I used so far, the program reads the file, char by char. But you can read it word by word, this way:

char str[30]; //the word can’t be more than 30 characters long
while(!file.eof())
{
file >> str;
cout << str;
}

You can also read it line by line, this way:

char line[100]; //a whole line will be stored here
while(!file.eof())
{
file.getline(line,100); //where 100 is the size of the array
cout << line << endl;
}

You now might be wondering which way to use? Well, I’d recommend you to use the line-by-line one, or the first that I mentioned- the one which reads char-by-char. The one that reads word-by-word is not good idea, because it won’t read the new line. So if you have new line in the file, it will not display it as a new line, but will append the text to the existing one. But using getline() or get() will show you the file, just as it is!

Now, I will show you how to check if the file opening was successful or not. In fact, there are few good ways to check for that, and I will mention them. Notice that where there is X, it can be either “o”, either “i” either nothing (it will then be fstream object).

Example 1: The most usual way

Xfstream file("filename.txt");
if (!File)
{
cout << "Error opening the file! Aborting…\n";
exit(1);
}

Example 2: If the file is created, return an error

ofstream file("file_non_existing.txt", ios::nocreate);
if(!File)
{
cout << "Error opening the file! Aborting…\n";
exit(1);
}

Example 3: Using the fail() function

ofstream file("filename.txt", ios::nocreate);
if(file.fail())
{
cout << "Error opening the file! Aborting…\n";
exit(1);
}

The new in Example 3, is the fail() function. It returns a nonzero value if any I/O error (not end of file) has occurred.

I would also like to mention about something , that I find to be very useful! For example, if you have created a file stream, but you haven’t opened a file. This way:

ifstream file; //it could also be ofstream

This way, we have a handle, but we still have not opened the file. If you want to open it later, it can be done with the open() function, which I already covered in this tutorial. But if anywhere in your program, you need to know if currently there is an opened file, you can check it with the function is_open(). It retunrs 0 (false) if a file is not opened, and 1 (true) if there is an opened file. For example:

ofstream file;
file.open("filename.txt");
cout << file.is_open() << endl;

The code above, will return 1, as we open a file (on line 2). But the code bellow will return 0, because we don’t open a file, but just create a file stream handle:

ofstream file;
cout << file.is_open() << endl;

This way we can use the functions and other things provided.

File I/O streaming in C++ Introduction

Introduction: This tutorial will start with the very basis of File I/O (Input/Output) in C++. After that, I will look into aspects that are more advanced, showing you some tricks, and describing useful functions.

You need to have good understanding of C++, otherwise this tutorial will be unfamiliar and not useful to you!

Your Very First Program

I will first write the code, and after that, I will explain it line by line. The first program, will create a file, and put some text into it.


#include
using namespace std;


int main()
{
ofstream SaveFile("filename.txt");
SaveFile << "Hello World!";
SaveFile.close();
return 0;
}


This program will create the file filename.txt in the directory from where you are executing it, and will put “Hello World!” into it.

Here is what every line means:

#include - You might have already known the use of this. It includes functions from specified header file. In this file, are declared several classes, including ifstream, ofstream and fstream, which are all derived from istream and ostream.

ofstream SaveFile("filename.txt");
1) ofstream means “output file stream”. It creates a handle for a stream to write in a file
2) SaveFile – that’s the name of the handle. You can pick whatever you want
3) (”filename.txt”); - opens the file cpp-home.txt, which should be placed in the directory from where you execute the program. If such a file does not exists, it will be created automatically.
Now, let’s look a bit deeper. First, I’d like to mention that ofstream is a class. So, ofstream SaveFile(”cpp-home.txt”); creates an object from this class. What we pass in the brackets, as parameter, is actually what we pass to the constructor. It is the name of the file. So, to summarize: we create an object from class ofstream, and we pass the name of the file we want to create, as an argument to the class’ constructor. There are other things, too, that we can pass, but I will look into that, later.

SaveFile << "Hello World!"; - "<<" looks familiar? Yes, you’ve seen it in cout <<. This ("<<") is a predefined operator. Anyway, what this line makes, is to put the text above in the file. As mentioned before, SaveFile is a handle to the opened file stream. So, we write the handle name, << and after it we write the text in inverted commas. If we want to pass variables instead of text in inverted commas, just pass it as a regular use of the cout <<. This way:
SaveFile << variablename;

SaveFile.close(); - As we have opened the stream, when we finish using it, we have to close it. SaveFile is an object from class ofstream, and this class (ofstream) has a function that closes the stream. That is the close() function. So, we just write the name of the handle, dot and close(), in order to close the file stream!

Notice: Once you have closed the file, you can’t access it anymore, until you open it again.

That’s the simplest program, to write in a file. It’s really easy! But as you will see later in this tutorial, there are more things to learn!


Reading From A File:

You saw how to write into a file. Now, when we have filename.txt, we will read it, and display it on the screen.

First, I’d like to mention, that there are several ways to read a file. I will tell you about all of them later. For now, I will show you the best way.


#include
void main()
{
ifstream OpenFile("filename.txt");
char ch;
while(!OpenFile.eof())
{
OpenFile.get(ch);
cout << ch;
}
OpenFile.close();
}


You should already know what the first line is. So, let me explain you the rest.

ifstream OpenFile("filename.txt"); – I suppose this seems a bit more familiar to you, already! ifstream means “input file stream”. In the previous program, it was ofstream, which means “output file stream”. The previous program is to write a file, that’s why it was “output”. But this program is to read from a file, that’s why it is “input”. The rest of the code on this line, should be familiar to you. OpenFile is the object from class ifstream, which will handle the input file stream. And in the inverted commas, is the name of the file to open.

Notice that that there is no check whether the file exists! I will show you how to check that, later!

char ch; - Declares an array of type char. Just to remind you- such arrays can hold just one sign from the ASCII table.

while(!OpenFile.eof()) – The function eof() returns a nonzero value if the end of the file has been reached. So, we make a while loop, that will loop until we reach the end of the file. So, we will get through the whole file, so that we can read it!

OpenFile.get(ch); - OpenFile is the object from class ifstream. This class declares a function called get(). So, we can use this function, as long as we have an object. The get() function extracts a single character from the stream and returns it. In this example, the get() function takes just one parameter- the variable name, where to put the read character. So, after calling OpenFile.get(ch) it will read one character from the stream OpenFile, and will put this character into the variable ch.

Notice: If you call this function for a second time, it will read the next character, but not the same one! You will learn why this happens, later. That’s why, we loop until we reach the end of the file! And every time we loop, we read one character and put it into ch.

cout << ch; - Display ch, which has the read character.

File.close(); - As usual, we need to close the file atlast using this close() function.
Notice: Once you have closed the file, you can’t access it anymore, until you open it again.
That’s all! I hope you understood my comments! When you compile and run this program, it should output:

“Hello World!”

If you guys are much interested in this, then you have two more topics called Managing I/O streams and I/O flags. Have fun reading C++.

Sunday, March 14, 2010

Open Social

Hi guys!

These days almost everyone are using Orkut, facebook and many other social networking sites. One of the organization is supporting them with necessary interfaces to communicate among themselves. Its called OpenSocial. Lets have some introduction about its enterprise view only. In my next blog, I will give complete details of it.

Before diving into how OpenSocial can benefit the enterprise, it is helpful first to understand OpenSocial's history, especially the evolution from its Social Networking Site (SNS) roots into a broader platform for social interaction and application interoperability. As social networking became more popular, there was increasing pressure on these sites to add differentiated capabilities and attract more users. A business model was also emerging where vendors wanted to offer their services into these social networks. Before OpenSocial, the notion of deploying an application into a social network was strictly a proprietary exercise. What's worse, if they had applications for each platform, they had to maintain them, account for programming model dissimilarities, translate each one, and so on.

OpenSocial provided a solution to these problems by serving as an open, community-driven, set of specifications that standardized the construction and deployment of social applications. It provided a common programming and deployment model for Web 2.0 user interface components, for accessing social graphs, and for working with activities. Applications built to the OpenSocial specification could be deployed into any social network that complied with the specification.

In November of 2007, OpenSocial was launched. Independent developers finally had a framework they could use to build applications that would run in any OpenSocial compliant site. OpenSocial was quickly adopted by many traditional social network sites including MySpace, Orkut, hi5, and Ning. The population of end-users - the people running OpenSocial applications on various OpenSocial container sites - began to grow exponentially. In addition to a strong upsurge in the overall population of end-users, the OpenSocial global developer community also blossomed and quickly provided numerous new applications for these new OpenSocial containers to plug into their sites. The benefit to the community of social network providers was immediate - they now had a vast pool of OpenSocial developers from which to draw from in order to enhance their application offerings. Similarly, developers benefited by being able to deploy their applications to a variety of social network, and not just one targeted specifically.

As OpenSocial continued its fast paced growth in the first year, so did its evolution. In the early days of OpenSocial, its primary focus was consumer social networks. In mid 2008 however, an architectural enhancement known as the "REST APIs" was introduced in version 0.8 of the OpenSocial specification. The REST APIs provided a programmatic mechanism for integrating back end systems, a common requirement within enterprises. In 2009, as version 0.9 was released, OpenSocial's overall end user population had reportedly reached approximately 800 million. This number is based on the self reported end user populations of containers that now support OpenSocial.

Need to read more on this view. Have fun of it by clicking here

Friday, March 12, 2010

What & How first article/post to be?

I would like my first article to give you some brief points how to write an article.
These are the few important points to remember before writing an article.

1. Research your topics thoroughly. Gather as much information as possible on the topics that you're about to explore. I am sure that you'll be able to find a lot of websites and other online resources on anything that you can think of. It's crucial that you do not leave any stone unturned. Your blog posts will become more valuable to the eyes of your readers if they contain complete, in-depth information.

2. Plan ahead. Don't start writing your blog posts without creating an outline. This will help you organize your material and will serve as your very own roadmap. List down all the information that you might discuss on your articles. Then, decide which ones are really important to your readers. List these down in a logical manner.

3. Be different. Ensure that your blog posts are way different and way better compare to your competitors'. They must contain more information, they should be more interesting to read, and they should be more valuable.

4. Learn from expert bloggers. I am sure you want to follow their footsteps. Start by knowing what they know and by doing what they're doing. Visit their blogs on a regular basis and identify the writing techniques that they're using. Also, identify the elements that they are utilizing to make their blog posts stand out from the crowd.

5. Spice up your posts. You can do this by using visuals like relevant images, statistics, and graphics that are pleasing on the eyes. However, make sure that you do not overdo this. 1-2 visuals should be enough for a very short blog post.

If you wanna learn more about this, you could download the complete explaination from here