You are here:

C++/problem in c++ file handling

Advertisement


Question
Sir,
The coding u mentioned didn't seem to run. When I compiled the program, the compiler was declaring that is_open wasn't an object of fstream.h.

-------------------------

Followup To

Question -
Hello sir,
I'am trying to write a program that can find the file size of any file stored in the computer.
I tried the follwing coding...

void main()
{
fstream obj;
int count=0;

obj.open("C:/Program Files/abc.txt",ios::in|ios::out);

while(!obj)
count++;

cout<<"File Size: "<<count;
}

But this didn't seem to work....I'am keen to know it's solution! Where I'am I making a mistake and what is the correction?

Thanx

Answer -
Well I would suggest you check out your C++ IOStream reference! The obvious problem is:

   while(!obj)
       count++;


Ignoring the rather meaningless name for the stream of obj, operator! for streams returns true if the stream has _failed_ due to formatting or bad errors. So your loop counts each time the stream is in the fail state. If you point it to a nonexistent file then the stream would be bad and presumably your program would loop for ever!

If your stream is good then it drops past the loop and exits the program.

I would use the stream member functions is_open, eof and good to ensure you know what is going on:

   obj.open("C:/Program Files/abc.txt",ios::in|ios::out);

   if ( obj.is_open() )
   {
       while( obj.good() )
       {
         ++count;
       }

       if ( obj.eof() )
       {
         cout << "File Size: " << count;
       }
       else
       {
         cerr << "Error while counting file size.
";
       }
   }
   else
   {
       cerr << "Unable to open file.
";
   }

If you are using VC++ then you can use the _filelength or _filelength64 runtime library functions (note the _ prefix indicating they are non-standard). The following is a modified MSDN library example:

   #include <io.h>
   #include <fcntl.h>
   #include <share.h>
   #include <sys/stat.h>
   #include <iostream>

   // ...

   int fh;

   // Open a file
   if ( _sopen_s( &fh
         , "C:/Program Files/abc.txt"
         , _O_RDONLY
         , _SH_DENYNO
         , _S_IREAD
         ) == 0
      )
   {
       std::cout << "File length: "
         << _filelength( fh ) << " bytes.
";
       _close( fh );
   }

_filelength and _filelength64 require a file handle, and so the file must be opened with _open or _sopen_s or their UNICODE equivalents and closed using the _close function. Note that I have not tried my modified example so sorry for any mistakes. You can find more on these functions in the MSDN library which you can find online at http://msdn.microsoft.com/library/. I reiterate that these are non-standard functions so runtime libraries for other compilers may not support them or use different names.

Hope you find this useful.  

Answer
My answers always assume standard C++ unless I know for certain the particular short comings of the questioner's compiler and/or standard library implementation. That is except where I mention specific compiler specific features like the _filelength example in my original answer.

fstream.h is the old pre-standard header for C++ file streams. Like all standard C++ headers the header for standard C++ file streams has no .h extension i.e. it is called fstream. Unless your compiler is really old (pre-VC++ 6 for example) you should be using these headers. Some compilers ship with both standard and pre-standard versions of library components to allow old code to be compiled with newer versions of compilers.

E.g.
----
Use:

#include <fstream> // GOOD

and not:

#include <fstream.h> // !BAD!

The C++ standard library supports features from the C standard library and these headers will be shipped as both a C-style version (e.g. stdio.h) and a C++ version style version (e.g. cstdio). You will note that the name of the C++ style header removes the .h extension and adds a c prefix. Of the headers listed in the modified MSDN example from my original answer none of them are standard C or C++ except iostream.

As you have not stated what compiler and version you are using I cannot be more specific. If you must use the pre-standard IOStreams either because you cannot or do not wish to get a more up to date compiler and/or C++ library or because your project has too much code invested in the old C++ dialect then I suggest you check out the documentation for the IOStreams implementation you are using to see if there are equivalents to the functions I mention.

If however you have an old compiler and C++ library and would like to upgrade then you might like to take a look at http://www.thefreecountry.com/ specifically http://www.thefreecountry.com/compilers/cpp.shtml in particular note the link to the express version of Microsoft Visual C++ 2005 – their most up to date compiler with libraries and development environment. If you would like to keep your compiler by maybe see if you can upgrade your C++ library then you might like to check out http://www.stlport.org/.  

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.