fstream

I've read the article on here about it many times before, but I'm still confused about it. Can someone help explain it to me? I know it has to deal with files and whatnot, but I'm a little confused on all the functions like opening and closing a file, and being able to do things with the file.
Last edited on
closed account (zb0S216C)
It's quite straight forward when you simplify it. fstream acts as an interface for the file it's associated with.

fstream::open() attempts to open the file with the specified name. If the file doesn't exists, it creates one. Of course, this only occurs with std::ofstream. If the attempt succeeds, true is returned and std::fstream attains a handle to the file.

Closing the file is as simple as opening it. When fstream::close() is invoked, fstream lets go of the file.

A write operation places more information into the file via the I/O (input/output) stream. A read operation reads each byte sequentially and converts the bytes to the types that shall receive the read data.

Wazzak
Last edited on
Arighty. But whats the whole deal with .txt and .bin, and why did someone say .bin was better?
closed account (zb0S216C)
.txt is a simple format which is commonly used for basic file I/O. .bin is considered better since it's in binary (machine language). Here's a few links:

http://www.google.com/search?gcx=c&sourceid=chrome&ie=UTF-8&q=.bin#sclient=psy-ab&hl=en&biw=1034&bih=875&source=hp&q=C%2B%2B+binary+file&pbx=1&oq=C%2B%2B+binary+file&aq=f&aqi=g1g-c3&aql=&gs_sm=e&gs_upl=1559l2200l0l2375l4l4l0l0l0l1l208l723l0.3.1l4l0&bav=on.2,or.r_gc.r_pw.,cf.osb&fp=eace23dd34db2182

http://courses.cs.vt.edu/~cs2604/fall02/binio.html

Wazzak
Last edited on
.txt and .bin is just file extensions and doesn't tell what's in the file. Often .txt is a text file and .bin is a binary file but it doesn't have to be like that.

A text file is better if you want people to be able to read it and possibly change it manually. A text file is often easier to get to work between different computers because you don't have to care about the sizeof variables, endianness and other platform dependent stuff.

A binary file is better if you don't want people to look inside the file or you don't care. A binary file is often smaller than a textfile and loads faster.

If you forget to call close() on a fstream it will automatically close the file in the destructor. If you are opening the file right after you created your fstream you can just pass the arguments you passed to open() to the fstream constructor and you don't have to call open.
Topic archived. No new replies allowed.