You are here:

C++/problem in using DevC++

Advertisement


Question
Hi,
I had previously asked you many questions. Thanx for response. I am new to the world of programing.

I was using Turbo C++ compiler 16 bit enviornment(windows Xp). But now found it inconvenient and now switched over to DevC++. Also I want to get the '.exe' file, which I think will be possible by using DevC++. Is it possible to get '.exe' file by using turboC?
Some of the portion of the program is given below-

#include<fstream>
#include<iostream>
#include<conio.h>
#include<stdlib.h>
#include<string>
#include<iomanip>
#include<stdio.h>
#include<limits>
#include<windows.h>

using namespace std;  
int main()
{
std::ofstream outfile;
outfile.open("WR_TEDs.DAT",ios::binary|ios::out);
if(!outfile)
  {
  cout<<endl<<"unable to open ";
  outfile.close();
  getch();
  }
  else
  outfile.close();

std::fstream infile("RD_TEDSs.DAT");
infile.open("RD_TEDs.DAT",ios::in|ios::out|ios::binary);
   if(!infile)
  {
  cout<<endl<<"unable to open file";
  infile.close();
  getch();
  }
  else
  infile.close();
getch();
}

IN CASE OF DevC++:
In this case, it shows no errors or warnings. The outfile "WR_TEDs.DAT" gets created and executed properly. The infile
"RD_TEDs.DAT" doesn't get created and it prints 'unable to open file' on screen as given in program. I have tried a lot but the infile is unable to get created while outfile gets created. Please help me on how to open a binary file in both the input and output modes in DevC++. (In the program later I also want to remove this file.)

IN CASE OF Turbo C:
above program gets executed properly without any error or warning, and both files get created.

-thankx.
abhijeet.

Answer
The differences you are seeing are differences between the probably pre ISO standard C++ IOStreams implementation used by the old 16-bit Borland C++ product (sometimes these are called "traditional IOStreams") and that of the more up to date and ISO C++ standard compliant C++ IOStreams implementation of the GNU C++ implementation used by DevC++ (the MinGW port see http://www.mingw.org/).

Your first obvious problem is that you have attempted to open the in/out file _twice_:

   std::fstream infile("RD_TEDSs.DAT");                        // create and attempt to open file
   infile.open("RD_TEDs.DAT",ios::in|ios::out|ios::binary);    // attempt to open file again

The first attempt to open the file during construction will attempt to open the file with the default std::fstream open modes of std::ios_base::in|std::ios_base::out (or, more conveniently for us std::ios::in | std::ios::out). This will _fail_ if the file RD_TEDSs.DAT does _not_ exist, as opening for reading requires the file to exist first. The second attempt to open the file will fail for the same reason.

If however the file RD_TEDSs.DAT did happen to exist for some reason then the first attempt will succeed and the second attempt fail - because the file is already open so the _operation_ fails. The file would however be open, from the initial open during construction. A file stream can be tested to see if it is connected to an open file using the is_open operation:

   if ( infile.is_open() )
   {
   // ...
   }

To open a file for input and output and creating the file if it does not exist we have to specify std::ios_base::trunc (or std::ios::trunc, or as you have a using namespace std directive in effect, just ios::trunc). This will of course truncate the contents of any existing file but will create the file if it does not already exist. So either do:

   std::fstream infile("RD_TEDSs.DAT",ios::in|ios::out|ios::trunc|ios::binary);

Or:

   std::fstream infile;
   infile.open("RD_TEDs.DAT",ios::in|ios::out|ios::trunc|ios::binary);

You can then check the stream is connected to an open file using the is_open() operation:

   if ( infile.is_open() )
   {
       std::cout << "infile opened OK.\n";
   }

You can check the stream state after the last operation is OK like so:

   if ( infile )
   {
       std::cout << "infile not in a bad or failed state.\n";
   }

Or conversely if it is not OK, as you were doing,

   if ( !infile )
   {
       std::cout << "infile is in a bad or failed state.\n";
   }


A stream is bad if it encountered an unrecoverable error. A stream is failed if the last operation failed but is recoverable - this is most commonly encountered when performing formatted input using the >> operator and the input characters are illegal for the format for the receiving type (e.g. non-digit characters other than - or + in integer input data).

The above test using !infile is equivalent to:

   if ( infile.fail() )
   {
       std::cout << "infile is in a bad or failed state.\n";
   }

The stream state testing member functions are:

  strm.eof()   -   returns true if end of file reached
  strm.fail()  -   returns true if there was a bad, fatal error or recoverable failure
  strm.bad()   -   returns true if there was a fatal error
  strm.good()  -   returns true if not bad, fail or eof

I also noticed that you are including many more header files than this piece of code requires. In particular do not include windows.h unless you are writing MS Windows specific code. In fact your code only required <fstream> and <iostream> and the non-standard <conio.h> for getch (all calls to which I commented out so I could build your code using the GNU compiler under Linux).

Also please pay attention to indentation and general code layout. The indentation of your code was all over the place making your code look very untidy and sloppy. It may not matter to the compiler but it does to us humans - well laid out code aids readability. In the same way I would hope you would want to look smart if you presented yourself socially it is polite and helpful to present your code in a smart and tidy fashion for the world to see, and of course shows you care enough to be bothered - if you cannot be bothered to present your code as well laid out and easy to get into as possible way why should anyone else bother to try to understand it if they do not have to (e.g. AllExpert volunteer question answerers like me)?

In any case I hope this helps.

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Ralph McArdell

Expertise

I am a software developer with more than 15 years C++ experience and over 25 years experience developing a wide variety of applications for Windows NT/2000/XP, UNIX, Linux and other platforms. I can help with basic to advanced C++, C (although I do not write just-C much if at all these days so maybe ask in the C section about purely C matters), software development and many platform specific and system development problems.

Experience

My career started in the mid 1980s working as a batch process operator for the now defunct Inner London Education Authority, working on Prime mini computers. I then moved into the role of Programmer / Analyst, also on the Primes, then into technical support and finally into the micro computing section, using a variety of 16 and 8 bit machines. Following the demise of the ILEA I worked for a small company, now gone, called Hodos. I worked on a part task train simulator using C and the Intel DVI (Digital Video Interactive) - the hardware based predecessor to Indeo. Other projects included a CGI based train simulator (different goals to the first), and various other projects in C and Visual Basic (er, version 1 that is). When Hodos went into receivership I went freelance and finally managed to start working in C++. I initially had contracts working on train simulators (surprise) and multimedia - I worked on many of the Dorling Kindersley CD-ROM titles and wrote the screensaver games for the Wallace and Gromit Cracking Animator CD. My more recent contracts have been more traditionally IT based, working predominately in C++ on MS Windows NT, 2000. XP, Linux and UN*X. These projects have had wide ranging additional skill sets including system analysis and design, databases and SQL in various guises, C#, client server and remoting, cross porting applications between platforms and various client development processes. I have an interest in the development of the C++ core language and libraries and try to keep up with at least some of the papers on the ISO C++ Standard Committee site at http://www.open-std.org/jtc1/sc22/wg21/.

Education/Credentials

©2012 About.com, a part of The New York Times Company. All rights reserved.