![]() |
| ||
| fstream Tutorial File I/O Intro File handling is as simple as writing in a book, much easier to modify and find. It's so simple people get confused with it :-). Welcome to the world of file handling. We will use the c++ fstream classes to do our file handling. So, what is a file? A file is just a bunch of bytes stored on a hardisk. Some have a specific structure others dont. Files are used to save info so that it can be retrived later for use. [I dont think you will want to save 100 people's address in memory will you]. Types of Files Actually there are only two. Text files and binary files. In text files data is stored as readable chars and binary file are in machine language. So if you output abc123 to a text file you will see abc123 but in a binary file you may see only a bunch of black blocks if you use notepad. The binary files are smaller in size. Fstream.h fstream.h provides simultaneous input and output through ifstream, ofstream and fstream. ifstream - open the file for input Writing to a file Relatively very simple. Steps:
Eg Program 1.1 #include <fstream.h> Methods for Writing to a file The fstream class is derived from the iostream classes, so you can use ofstream variables exactly how you use cout. So you can use the insertion (<<) operator and the put(). Usages: Reading from a file Almost the same. Steps:
Eg Program 1.2 #include <fstream.h> Methods for Reading a file The fstream class is derived from the iostream classes, so you can use fstream variables how you use cin.So you can use the extraction (<<) operator and the put(). Usages: Notes: 1. The file handles can be used like: ofstream file("fl.txt");You will use the constructor for opening a file.I would not recommend using this not because it works less well or anything but in most cases it will improve code clarity and prevent errors when you are handling multiple files. If a file handle is used more than once without calling a close() in between them there will be errors. This is just provided for info sake if you need to use it in a hurry or in something small. 2. Never ever declare a fstream variable globally. It is a bad habit. If you forget to close it next time you run the program it will show access errors to the C: drive (or which ever drive you use) and you will have to restart the computer. Declare them within funtions or classes and close them when their use is over. 3. If you are doing databases or any file handling for that matter never put any file i/o into classes. It will simply complicate debugging and you may also open a single file multiple times with difffrent objects at the same time. This is definitely not what we want. Classes are only to be used when you have to minimal file i/o but still I recommend you use normal funtions. 4. ifstream stands for input stream and can only be used for input. 5. ofstream stands for output stream and can only be used for output. 6. Any variable declared with ifstream,ofstream or fstream is called a file handle. That wraps up the simple very stuff. You will not use them much unless you are working with text files or in a small project. Now we will move on to fstream which is more flexible and will be most used. It's easy if you look at it logically. Dynamic file access The file streams we discussed have a limitation, they can only do input or output at a time. fstream provides us with a way to read, write randomly without having to close and reopen the file. It has great flexibility involving a bit more work with returns being ten fold. Hey, you cant have everything for free (what fun would it be if everything was handed to you). Lets look at how a file can be opened with fstream. Program Example 1.3 void main() Notice anything new? The ios::--- are attributes which define how a file should be opened. List of Attributes Notes
Now we know how to open a file with fstream. Cool, now come read and write. Reading and Writing with fstream The two funtion are exactly similar in usage and simple to understand file.write(char *,int); //for writing Until now we have only been able to use strings and ints to write/read. Most databases will want to store data in structures or classes. If we had to write a seperate function to split and write each member, brrr horrors. C++ goes to be very nice and provides us with a way to write entire classes or structures with little work [/CODE] struct x { int i; char a; char s[10]; }data; file.write((char*)&data,sizeof(x)); file.read((char*)&data,sizeof(x)); [/CODE] Hold on, what the heck is the char * thingy???. That's called typecasting. Quite an interesting subject actually. It means converting one data type to another. Here it is converting struct x into a char pointer and it's address is passed to the funtion. If anybody wants to know more, well tell! The rest is simple. You pass the size of the structure which can be found out by using sizeof(); Eg: cout<<"\nInt:"<<sizeof(int); Now instead of going more yack yack I show you an example which should explain a lot more. Sigh "A picture is worth a thousand word, source is worth a million bytes" Example Program 1.4 #include <fstream.h> Got more doubts now than what was cleared? Good, doubts are the first step towards knowledge. (If you happen to be of an opinion that a teacher should explain everything, sorry it's just not my style. I want thinking students not tape recorders) Note:
------------------------- PART II ------------------------- Random File Access With fstream we work with 2 file pointers, read and write. By moving these pointers we go access any part of the file at random. See below: Reading Both tellp() and tellg() don't take any parameters but return where the pointer location in bytes. Eg. The seek pointers take 2 parameters Eg.
Note:
Intro This is another area people find difficulty. I figured it out myself without any help what so ever. I also learned file handling a year before my classmates by looking at an elder's text which contained only vague descriptions so I guess my eagerness to learn had something to do with it. I have always loved computers and programming. I fell in love with QBasic the moment I saw it. C++ stole my heart then. Ah, programming is a part of my soul. And even when I got my own text book nothing what so ever was mentioned about random file access except a short and vague description about the 2 functions and the options. There was no reference what so ever about locating individual records. I can't guess why! Reminds me of a saying "when old, one forgets how it is to be young". That maybe a cause :D. [oh, this reminds me, almost every comp guy/gal I know works late at night. I do too when I don't have much time in the mornings. We should stop this. Never work in the dark without enough light, nor stay up too late. If your eyes feel slightly sleepy,SLEEP. No more than 1:30 AM at the most, I am thankful I been able to do most of this] Locating Individual Records Problem area. Let start at the beginnings. Ever seen a graph paper ?.It has a lot of tiny, small, medium and large sized squares. Also each is being made from the tiniest square. What that got a do with files? Well when you use databases you will almost always use structures and they are always the same size (in that particular database). That means like in the program in Part I all the records are with that one class and when you write it to a file it will still be the same size even if you filled it or not. It's like your water bottle. Whether it's full, half or even empty it will always take up the same space in your bag. Get it? How do you find the size of any data type ?Easy. Size_Of_Data_Type = sizeof(Data_Type); //sizeof is a reserved keyword in C++. Ok, how will that help us find a record? Well all records are of the same size, they start at zero. They can be thought of as an array too and the concept is similar to how you use normal pointers. Eg. A struct is 20 bytes in size. The first rec starts at byte zero, the second at byte 20, the next at byte 40 ...... and so on Eg. Program 2.1 file.seekg( Rec_no * sizeof(Data_Type),ios::beg); Simple as that. Note:
I think now you get random access. How about finding the total number of records in a database? Eg. Program 2.2 file.seekg(0,ios::end); //move to the end of the file We divide the total file size by the size of the structure to find the number of record. Simple maths eh? That's it you have full knowledge of how to handle fstream. Now all you need is creativity, so use it. I won't tell you all, so think. Knowledge can be gained from others but wisdom only from yourself (and from God). Ah, I love this. Here is some work for you.
Error Checking These are some funtions that help to keep track of errors in your database if any Error Funtions All are member funtions and are used as file_handle.errror_funtion() Eg. char ch; You should have understood what those funtions are for. Implement them when you do you file handling. good() should be called after opening a file to see it has been opened properly. bad() is the opposite of good(). Encryption Aha, any decent database program must encrypt its files. Just open up any of the files from the example programs with notepad and you will be able to see the text. We definitely don't want people to see that. With encryption you can scramble the text so people can read it. Now there are a lot of encryption schemes and a lot of other methods for protecting data. I will just show you a couple of methods. Binary Shift The simplest of all. In this you increase or decrease a char by a number. void b_shif(char *s,int n) XOR Another type of encryption. Exclusive-OR encryption, is almost unbreakable through brute force methods. It is susceptible to patterns, but this weakness can be avoided through first compressing the file (so as to remove patterns). This encryption while extremely simple, is nearly unbreakable. int xor(char *string, char *key) Encrypt an entire structure void struct_enc_xor(char *str,char *key,int sz) Use it exactly how you used read(). Eg. struct_enc_xor((char*)&cRec,"password",sizeof(DtbRec)); Exit Encryption is a very interesting topic. A lot of research has gone into it. If you are interested there are lot of pages on the web which describe encryption and various schemes. Then there is stenography, the art of hiding info in any file like text within a bitmap or an mp3. Have fun researching. |
| ||
| Re: fstream Tutorial Now here's a printer friendly version(has a few fixes to part I) http://www.polarhome.com:793/~xlock/txt/fstream.txt |
| ||
| Re: fstream Tutorial Cool. In addition, DaniWeb users can always use the Thread Tools dropdown and then select Printable Version for any thread :) |
| ||
| Re: fstream Tutorial Hello! I have a little question. Lets say, I have a file called word.txt and it contains 100 over words. How do I add a new word and SAVING it so I can use this word from this file in future? Thanks |
| ||
| Re: fstream Tutorial Quite simple really,just open word.txt with ios::app (append) added to the options when opening the file.That will automaticaly put the file pointer to the end of the file and you can just write to it normally. Another way is to open the file and use filehandle.seekp(0,ios::end); to move the pointer to the end of the file and then write the output you want to the file and it will still be at the end. Checks the tut for the list of options,I covered them there. Btw,then close the file when you exit or are finished with using it.There you go a new word was added to the file. |
| ||
| Re: fstream Tutorial A little update.My site URL is now: http://xlock.hostcubix.com/ |
| |||
| Re: fstream Tutorial Interesting tutorial, however I did notice a few errors here and there. Quote:
Quote:
Quote:
It was a very interesting tutorial though. You did a lot with fstream that I wouldn't have thought of. |
| ||
| Re: fstream Tutorial True enough,about certain char being translated in the text mode.But let me remind that file<<"abc123" is a string.Try doing file<<"abc"<<123<<(char)123; See what happens, one forgets and assumes a bit somethimes. Quote:
This may not be true on diffrent compilers (or even the same one's diffrent versions).That could have happened due to a lot of reasons.But it a good practice to alway close a file handle before you exit .I just said something which might possibly happen, :). I love the fstreams too.Thanks so much Jubulani. |
| ||
| Re: fstream Tutorial Oops, my mistake. Calling 'open()' on an open file stream does cause errors. Sorry about that. And, true, always better safe than sorry. :) |
| ||
| Re: fstream Tutorial Yea, prevention is better than cure ;) |
| All times are GMT -4. The time now is 12:59 pm. |
Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2009 DaniWeb® LLC