Solved

C++ fstream

Posted on 2010-11-25
20
813 Views
Last Modified: 2012-05-10
I can't get the file to open in the code below...
The file doesn't already exist, but surely the code will handle that?
I want to open it in text mode - is it necessary to include the ".txt" suffix in the file name?
Any ideas welcome?
#include <fstream.h>
void    save_the_deal()
{
   char      test_file_name[] = {"testfile_5.txt"};
   fstream io;
   io.open(test_file_name, ios::in | ios::out);
   if(!io)
   {
      cerr << "Unable to open "<<test_file_name<< "\n";
    }
return;
}
Borland C++ Builder / Windows 7.
0
Comment
Question by:VaughanMx
  • 8
  • 6
  • 3
  • +2
20 Comments
 
LVL 53

Assisted Solution

by:Infinity08
Infinity08 earned 100 total points
ID: 34213326
>> is it necessary to include the ".txt" suffix in the file name?

If you want the file to have that suffix, then yes.


>> #include <fstream.h>

This header is deprecated. Use <fstream> instead (without the .h).


>>  char      test_file_name[] = {"testfile_5.txt"};

Make that :

        char      test_file_name[] = "testfile_5.txt";


>>    if(!io)

Better is to use is_open :

        http://www.cplusplus.com/reference/iostream/fstream/is_open/



Also : don't forget to close the file again.
0
 

Author Comment

by:VaughanMx
ID: 34213885
All Infinity08's suggestions incorporated - no benefit - file still fails to open.

What next to try?
0
 
LVL 86

Expert Comment

by:jkr
ID: 34213905
Are you writing anything to the file? Try
#include <fstream>

using namespace std;



int main()

{

    ofstream os("test.txt");



    os << "Test" << endl;



    return 0;

}

Open in new window

0
 
LVL 53

Expert Comment

by:Infinity08
ID: 34214210
Can you post the exact and complete code you are using ?
0
 
LVL 12

Assisted Solution

by:trinitrotoluene
trinitrotoluene earned 150 total points
ID: 34214676
the problem is that you aren't setting the stream's position indicator.

Try any of the following. It will work
io.open(test_file_name, fstream::in | fstream::out | fstream::app);

 io.open(test_file_name, fstream::in | fstream::out | fstream::ate);

 io.open(test_file_name, fstream::in | fstream::out | fstream::trunc);

Open in new window

0
 
LVL 8

Expert Comment

by:Subrat (C++ windows/Linux)
ID: 34215204
>>I can't get the file to open in the code below...
How you know? Is it printing "Unable to open "? If yes, then there might be some other error, like File doesn't exist.

+1 to Infinity.

// All Infinity08's suggestions incorporated - no benefit - file still fails to open.
No no no.... If file doesn't exist then wht code will do?
So you need to check whether file exist or not  before processing.

Hints: You can use Exception handling here...
0
 

Author Comment

by:VaughanMx
ID: 34217706
jkr
your example works OK.
The file is created, and text is written to it.

Subrat2009:
it is printing "Unable to open " ...
As I understand C++, the system is indifferent to the prior existence of a file which it is trying to open.
ios::nocreate,  ios::noreplace and ios::trunc are available to deal with any situation which arises.

trinitrotoluene:
I have tried setting the stream's position indicator - it doesn't seem to make any difference.

Infinity08:
Here is the code:
Note that I have included jkr's code in it, which still works OK.
But the fstream bit goes thru the Unable to open line.

//---------------------------------------------------------------------------
#include <vcl.h>
#include <fstream.h>
#include <iostream.h>
#pragma hdrstop
USERES("Project1.res");
//---------------------------------------------------------------------------

void save_the_deal()
{
 char test_file_name[] = {"testfile_5.txt"};
 fstream io;
 io.open(test_file_name, ios::in | ios::out);
 if(!io)
 {
 cerr << "Unable to open "<<test_file_name<< "\n";
 }
return;
}


WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
{
   try
   {
using namespace std;

    ofstream os("test.txt");
    if(!os)
      cout << "Failed to open";
    else                            save_the_deal();
      cout << "Opened OK";
    os << "Test" << endl;
    os.close();


       Application->Initialize();
       Application->Run();
       save_the_deal();
   }
   catch (Exception &exception)
   {
       Application->ShowException(&exception);
   }
   return 0;
}
//---------------------------------------------------------------------------
0
 

Author Comment

by:VaughanMx
ID: 34217971
A weird development...

When I use testfile_5.txt as a file name, it fails.

When I use fstream.out as a file name, it all works as it should. You may recognise the source of that name as the basic_fstream help document.

I have stried several variation s on my original file name - all of which failed.

So what is it that is so uniqely successful about "fstrem.out"?
0
 
LVL 53

Expert Comment

by:Infinity08
ID: 34217991
>> Here is the code:

I see that you haven't fixed anything I mentioned in my first post.


>> When I use testfile_5.txt as a file name, it fails.

If that file already exists, but you don't have permission to open it, then that could explain it.
0
 

Author Comment

by:VaughanMx
ID: 34218164
Infinity08:

Honest - I did fix things as per your first post - but since it didn't change the result, I reverted to my original code.

That file does not exist.

For testing purposes, I simply copied the sample code from the help document, and it worked - that's where the fstream.out came from.

So then I left their code in situ, and changed my filename to theirs - and it still works. That's good, but I really would like to know why.
0
Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

 
LVL 53

Expert Comment

by:Infinity08
ID: 34218278
>> but since it didn't change the result, I reverted to my original code.

Well, all fixes I suggested were actual problems with your code, so you shouldn't have reverted them ;)


>> That file does not exist.

So, can you open a text editor, and save a file with that name (testfile_5.txt) ?
0
 

Author Comment

by:VaughanMx
ID: 34218486
OK - I'll revert to your suggested code.

I just created a file (testfile_5.txt) using Wordpad - seemed quite happy with that - and it read back OK.
So I substituted that file name in the code I took from the help files, and it doesn't work. (And that's earlier in the function than your code - it never even got to that bit).
0
 
LVL 86

Expert Comment

by:jkr
ID: 34218504
Well, where do you expect the file to be created? Try an absolut path (e.g. "c:\\testfile_5.txt") and see if you can find it there.
0
 
LVL 53

Expert Comment

by:Infinity08
ID: 34218539
>> I just created a file (testfile_5.txt) using Wordpad - seemed quite happy with that - and it read back OK.

In the same directory where it fails creating the file with your code ?


>> So I substituted that file name in the code I took from the help files, and it doesn't work.

So, you still get an error message "Failed to open", right ?

Can you show your exact and complete current code, and indicate where exactly it fails ?
0
 
LVL 12

Expert Comment

by:trinitrotoluene
ID: 34219804
i don't believe it can't be anything to do with the stream indicator.

What happens when you try just a plain C fopen()?

http://www.cplusplus.com/reference/clibrary/cstdio/fopen/
0
 
LVL 12

Assisted Solution

by:trinitrotoluene
trinitrotoluene earned 150 total points
ID: 34219979
vaughan:

there definitely is a problem in obtaining a valid file handle....I was able to reproduce your problem. Let me know the outcome of the fopen and also try doing the following

1) modify your app so that it tries to open testfile5.txt or whatever in a completely different folder. Create the folder and check that the owner of the folder mirrors the account you have logged in with

for instance on Windows you may not be able to always modify folders/files created using the Trusted Installer account.

2)Check if your application works if it runs with elevated privileges?

3) check the failbit flag which gets set when the open fails
http://www.cplusplus.com/reference/iostream/fstream/open/

4)what happens if you do
.open("yourfilewiththecompletepath.whateverextension", fstream::binary);
 
0
 

Author Comment

by:VaughanMx
ID: 34221414
trinitrotoluene:
Thanks for all that.
1) I created a new folder under my username. I modified the program to create the testfile5.txt file, but it failed to open it - the folder is empty.
2) Elevated priveleges is new territory for me - a web reference seemed to indicate that it relates to Win 2000. I didn't do that bit.
3) cout << ios::failbit produced the answer 4 - even when the file opened OK. Maybe I'm not using it correctly?
4) it failed.
0
 
LVL 53

Expert Comment

by:Infinity08
ID: 34221420
How about http:#34218539 ?
0
 

Accepted Solution

by:
VaughanMx earned 0 total points
ID: 34242036
My thanks to all who participated in this - I still don't really understand the problem (well enough to explain it to anyone else), but have worked around it.
0
 

Author Closing Comment

by:VaughanMx
ID: 34276763
The question was taking too long to fix - I quit, and tried a more conventional (C not C++) approach.
Thanks to all who contributed.
0

Featured Post

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

This article shows you how to optimize memory allocations in C++ using placement new. Applicable especially to usecases dealing with creation of large number of objects. A brief on problem: Lets take example problem for simplicity: - I have a G…
Container Orchestration platforms empower organizations to scale their apps at an exceptional rate. This is the reason numerous innovation-driven companies are moving apps to an appropriated datacenter wide platform that empowers them to scale at a …
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now