473,383 Members | 1,929 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,383 software developers and data experts.

fstream - not creating files / not appending files / etc.

36
*sigh* Ok, I have two questions.

First, my setup: Win-doze XP-SP2; & Dev-C++ 4.9.9.2;

I recently started trying to use 'fstream' to work my input/output, and I noticed that using
the default constructor ( or 'open' method ) will not create a file.
Expand|Select|Wrap|Line Numbers
  1. ( fstream fstr("hello.dat") or fstr.open("hello.dat") )
I read on a site, that I needed to add these flags:
Expand|Select|Wrap|Line Numbers
  1. fstream fstr("hello.dat", ios_base::trunc | ios_base::out | ios_base::in);
This works, but it's long. Anyway, I tried to append to the file by changing 'trunc' to 'app',
and once again, my 'if' statement ran instead of the file being opened. ( code below... )

The ONLY way I can get fstream to work with a file that doesn't exist is the way I posted above.

So, I guess my question is: Why doesn't fstream work like ofstream, and just create the file?
( and does it really matter which you use: fstream or ofstream/ifstream? )

Expand|Select|Wrap|Line Numbers
  1. #include <iostream>
  2. #include <fstream>
  3.  
  4. int main()
  5. {
  6.   std::fstream fstr("hello.dat", std::ios_base::trunc | std::ios_base::in | std::ios_base::out);
  7.  
  8.   if (!fstr.is_open())
  9.   {
  10.     std::cerr << "ERROR: Could not open file.  Exiting...\n";
  11.     exit(1);
  12.   }
  13.  
  14.   fstr << "Hello from C++\n";
  15.  
  16.   char str1[20], str2[20], str3[20];
  17.  
  18.   fstr.seekg(0, std::ios_base::beg);
  19.  
  20.   fstr >> str1;
  21.   fstr >> str2;
  22.   fstr >> str3;
  23.  
  24.   std::cout << str1 << " " << str2 << " " << str3 << "\n";
  25.  
  26.   fstr.close();
  27.  
  28.   return 0;
  29. }
  30.  

Finally, question number:
2. I've seen different sites use different qualifying names for these flags, and I was wondering
if it matters which I use:
Expand|Select|Wrap|Line Numbers
  1.  
  2. fstream::app
  3. ios::app   // I believe this is the old way of using it, isn't it?  Now we've moved to:
  4. ios_base::app
  5.  
I've tested all three methods with different flags, and they all work.
I was just wondering which ones will continue to work later on.

Oh well, I appreciate any help you can give me.

Thanks,

-*Soneji
May 23 '07 #1
7 9892
Ganon11
3,652 Expert 2GB
For your first question, ofstream only creates a file because it does not depend on any information contained inside the file. All ofstream does is write to files, so if it creates a new, blank file, this doesn't interfere with writing information to it.

An ifstream cannot create files, because an ifstream is supposed to be reading data. If an ifstream is depending on information contained in a file, it doesn't make very much sense to create an entirely new, blank file - there would be no information to read!

Now, an fstream is like both an ofstream and an ifstream (that is, ifstream and ofstream are subclasses of fstream). That means that, even though an fstream is like an ofstream, it is also like an ifstream. Since you can use an fstream to read information, it doesn't make sense to create a new, blank file to read from - unless you specify that the fstream is for writing only, in which case it should (read: might?) work like an ofstream.

I don't know if there are any benefits to using ofstream/ifstream over fstream or vice versa, but I prefer ofstream/ifstream.
May 23 '07 #2
Soneji
36
Ahhh....

That clears up alot of the confusion I had about fstream, but any idea on why:
Expand|Select|Wrap|Line Numbers
  1. fstream fstr("hello.dat", ios_base::app | ios_base::out | ios_base::in);
doesn't append the file, but truncates it?

Thanks again,

-&Soneji
May 23 '07 #3
AdrianH
1,251 Expert 1GB
Ahhh....

That clears up alot of the confusion I had about fstream, but any idea on why:
Expand|Select|Wrap|Line Numbers
  1. fstream fstr("hello.dat", ios_base::app | ios_base::out | ios_base::in);
doesn't append the file, but truncates it?

Thanks again,

-&Soneji
Well, it doesn’t seem to on mine, in fact, it doesn't even open a file if it exists under g++. I would hazard a guess that it may be that using append with input isn't a defined function. Making a stream both input and output IMHO doesn't either (have you ever seen a stream of water run both directions in a single pipe?) but that is legacy. I would recommend using separate streams for your input and output, unless there is some compelling reason to do so.

This is the code I used for the test:
Expand|Select|Wrap|Line Numbers
  1. #include<iostream>
  2. #include<fstream>
  3. using namespace std;
  4. int main()
  5. {
  6.   fstream fstr;
  7.   fstr.open("hello.dat", ios_base::app | ios_base::out | ios_base::in);
  8.   if (fstr.is_open()) {
  9.     cout << "File open" << endl;
  10.   }
  11.   else {
  12.     cout << "Not open" << endl;
  13.   }
  14.   char buffer[100] = {};
  15.   fstr.getline(buffer, 100);
  16.   cout << "Buffer is: '" << buffer << "'." <<endl;
  17.   fstr.close();
  18.   return 0;
  19. }
  20.  
When I removed the app flag, it worked fine.

BTW, the reason some people used the different scope name for the flags is probably because of programmer preference or it was the way they were taught, It really doesn't matter.

The flags are defined in ios_base and all of the scopes you mentioned and more inherit from it. They all can use the flag, so all are valid. See here for a hierarchy.


Adrian
May 23 '07 #4
Soneji
36
Thank you both very much!
You have helped alot.

One more related question though:

Say I make an object to 'fstream', and use it to write to a file.
Ex: myObj.open( ios_base::trunc | ios_base::out );

If I want to read from the same file ( like take other info from it ), do I need to
'close' the file, then make another fstream object, and reopen it for reading?

Or can you change the original object to 'read' also?
( I'm off to try some tests. 8^) )

Ohhh... I didn't even think to look at "CPP.com" for the header that defined the
flags ( constants ).

That's quicker than what I ended up doing once:
The book ( grrr ) told me I would have to include 'cctype' myself. I forgot to
include it one time, and the program still compiled.
So I looked into the ones I did include to see which header included it.
( The path: iostream - ostream/istream - ios - iosfwd - cctype )

Man I love programming. :)

Anyway, Thanks again for the help.

-Soneji
May 24 '07 #5
AdrianH
1,251 Expert 1GB
Thank you both very much!
You have helped alot.

One more related question though:

Say I make an object to 'fstream', and use it to write to a file.
Ex: myObj.open( ios_base::trunc | ios_base::out );

If I want to read from the same file ( like take other info from it ), do I need to
'close' the file, then make another fstream object, and reopen it for reading?

Or can you change the original object to 'read' also?
( I'm off to try some tests. 8^) )

Ohhh... I didn't even think to look at "CPP.com" for the header that defined the
flags ( constants ).

That's quicker than what I ended up doing once:
The book ( grrr ) told me I would have to include 'cctype' myself. I forgot to
include it one time, and the program still compiled.
So I looked into the ones I did include to see which header included it.
( The path: iostream - ostream/istream - ios - iosfwd - cctype )

Man I love programming. :)

Anyway, Thanks again for the help.

-Soneji
Yes, you can read and write from the same file (as long as the OS opening permisions allow for it, I am not aware of the stream librararies opening for exclusitivity). But be warned, it will not stop you from reading and writing to the same place in the file, which could cause bad things to happen in your programme (think thread/process synchronisation).


Adrian
May 24 '07 #6
Soneji
36
Okies, Thanks!

Ohh... Sorry for the rant, I was tired.

Lates,

-Soneji
May 25 '07 #7
AdrianH
1,251 Expert 1GB
Okies, Thanks!

Ohh... Sorry for the rant, I was tired.

Lates,

-Soneji
Yeah, no prob. L8r. Good luck.


Adrian
May 25 '07 #8

Sign in to post your reply or Sign up for a free account.

Similar topics

3
by: Nullstyle | last post by:
Hi there guys. I need a little advice on how to create C++ header files using the Borland C++ 5.5.1 compiler. Thanks in advance.
10
by: draghuram | last post by:
Hi, Is there any special support for sparse file handling in python? My initial search didn't bring up much (not a thorough search). I wrote the following pice of code: options.size =...
2
by: simchajoy2000 | last post by:
I have found information about how to create res files but how do I create a resource file for VB.NET (*.resx files)? Joy
1
by: Arkady Renko | last post by:
Gday Guys I'm attempting to create zip files on the fly for some highly compressible, yet very large files stored on my Web server. At present I'm using a class from the Zend library by Eric...
4
by: Coleen | last post by:
Hi All :-) I'm not sure where to post this, but my organization is looking for a good software application that is not terribly expensive that allows you to create documentationand help files and...
0
by: edsfunsite | last post by:
Hi, I was wondering if anyone has ever had any problems with compiling c++ code and not having cl.exe create any obj files. ml.exe is giving me errors saying that it couldn't find the files on 4...
2
by: Oblivion | last post by:
Hi All, Can someone answer this for me? I don't seem have an luck getting an easy answer... I'm working with Tibco Designer (for Windows) to create EAR files and find it quite cumbersome. ...
1
by: Madhu Harchandani | last post by:
Hello i am working in a project in which i am using xnat technology in that data is entered through xml files only i need to enter 1000 records .so it is very cumbersome to create...
1
by: =?Utf-8?B?YW5raXQuc3Jp?= | last post by:
How can we Create or Delete a File on a Virtual Directory from asp.net ? The situation is I want the Application to Read and Write a Certain File on Virtual directory and when I do it from File...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.