• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 861
  • Last Modified:

C++ fstream

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
VaughanMx
Asked:
VaughanMx
  • 8
  • 6
  • 3
  • +2
4 Solutions
 
Infinity08Commented:
>> 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
 
VaughanMxAuthor Commented:
All Infinity08's suggestions incorporated - no benefit - file still fails to open.

What next to try?
0
 
jkrCommented:
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
Cloud Class® Course: SQL Server Core 2016

This course will introduce you to SQL Server Core 2016, as well as teach you about SSMS, data tools, installation, server configuration, using Management Studio, and writing and executing queries.

 
Infinity08Commented:
Can you post the exact and complete code you are using ?
0
 
trinitrotolueneDirector - Software EngineeringCommented:
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
 
Subrat (C++ windows/Linux)Software EngineerCommented:
>>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
 
VaughanMxAuthor Commented:
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
 
VaughanMxAuthor Commented:
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
 
Infinity08Commented:
>> 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
 
VaughanMxAuthor Commented:
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
 
Infinity08Commented:
>> 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
 
VaughanMxAuthor Commented:
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
 
jkrCommented:
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
 
Infinity08Commented:
>> 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
 
trinitrotolueneDirector - Software EngineeringCommented:
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
 
trinitrotolueneDirector - Software EngineeringCommented:
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
 
VaughanMxAuthor Commented:
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
 
Infinity08Commented:
How about http:#34218539 ?
0
 
VaughanMxAuthor Commented:
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
 
VaughanMxAuthor Commented:
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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: C++ 11 Fundamentals

This course will introduce you to C++ 11 and teach you about syntax fundamentals.

  • 8
  • 6
  • 3
  • +2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now