You are here:

C++/finding size of a file and delete

Advertisement


Question
I am doing program in CPP...
in that I have to find size of the file. Suppose size of the file is 10MB, I need delete it and create a new file of same name.

Answer
-------------------
FOLLOWUP
-------------------
I have read your ratings message and note that you may be using C or AllExperts have stripped the ++ (plus plus symbols) again, possibly replacing them with spaces.

If you are using C rather than C++ (C plus plus) then please note that although I have written pure C it was a long time ago.  For the last decade and more I have concentrated on C++ (C plus plus). You asked me as a C++ (C plus plus) expert not a C expert (there is I believe a separate question category for C) so you may have an answer that was not as relevant to you as it could have been.

In short if you ask a C++ (C plus plus) expert expect a C++ (C plus plus) biased reply. If you want a C biased reply then please ask a C expert.

Also note that often on embedded devices as you may be using you may not always have a standard language library available as the platforms (the devices) probably have a limited operating system if any and limited space and resources and quite possibly not much of a file system. In such cases you have to read the device and device software/firmware documentation to find out what facilities functions etc. are available.

Finally, I already spend quite a bit of time answering questions posted to me on AllExperts (yours took a couple of hours to formulate and type up). I also have my own life to get on with. It is with regret that I therefore cannot enter into any direct help relationships sorry.

However please feel free to post further questions to me on AllExperts. It was good to be able to actually answer a real question rather than reject questions from people wanting me to do their homework or similar!

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


The name of the language is C++ (C Plus Plus) not CPP - CPP is the name of a program that supports the C/C++ pre-processor functionality usually found on UN*X like systems.

At present in C++ there is no standard direct way to obtain the size of a file - although see my notes on Boost and TR2 near the end of my answer. Also note that the size of a file's data may well be different to its size on disk, due to the block (sector, cluster etc.) size used on the partition - the size on disk will always be the size of the file rounded up to the disk block allocation unit size. Then of course the file may be compressed etc.

However on UN*X like systems - such as Linux, Solaris, AIX etc. you can use the fstat function to obtain information on a file, one piece of which is its size in bytes. This call is also available in several forms for those using Microsoft Visual C++ on Microsoft Windows platforms. You call it like so:

   #include <sys/types.h>
   #include <sys/stat.h>
   #include <fcntl.h>

   // ...

   int file_desc( open("file/path/name", O_RDRW) );

   struct stat buffer;

   int status( fstat(file_desc, &buffer) );

   close( file_desc );

For Visual C++ you may need to prefix the names open, close, fstat and stat with an underscore (_open, _close, _fstat, _stat) as this indicates the names are non standard.

The fstat function returns a status of 0 if it worked and -1 if an error occurred in which case the errno global error value should be checked for the specific error (include <errno.h>).

Note that these calls and types are a C style API, however I have used a little C++ style in the definition and initialisation of some of the variables.

Please note that I do not have time to go into the details of such C library/UN*X style programming topics as errno in this answer. If you need to know more then please obtain good C and or UN*X programming references.

The stat struct filled in by fstat contains various data members (remember this is a C API so no class type functionality in the user defined types), one of which, st_size, is the size of the file in bytes:

   off_t  byte_size_of_file( buffer.st_size );

Again, for Visual C++ off_t may be prefixed by an underscore: _off_t.

Reference information on these types and functions can be found in the UN*X/Linux man (manual) pages which should be available locally on most systems running these operating systems, try for example entering the following command at a command prompt (terminal shell prompt):

   man fstat

They also can be found easily enough online (try typing fstat into Goolge or other search engine for example).

The Microsoft Visual C++ runtime library versions of these entities are documented in the MSDN (Microsoft Developer Network) library, which if you do not have a local copy on DVD can be found online at http://msdn2.microsoft.com/.

There are other ways to obtain this information that are OS specific. For example you could use the GetFileSize Win32 API function on a Win32 (Windows 9x, Me, NT, 2000, 2003, XP, Vista), having used the CreateFile and CloseHandle Win32 API functions to open and close the file. For more information on these functions please refer to the MSDN library reference.

A less obvious way to find the size of a file would be to seek to its end and ask for the current position in C++ we could do:

   #include <fstream>

   // ...

   std::ifstream in( "file/path/name" );

   in.seekg(0, std::ios::end); // seek to end
 
   std::ios::pos_type pos( in.tellg() ); // get file end position

However std::ios::pos_type is no longer an integer type (doh!), so we have to fall back on the C library equivalents:

   #include <cstdio>

   // ...

   FILE * in( fopen("file/path/name", "r") );
   
   int status( fseek(in, 0, SEEK_END) );

   long byte_size_of_file( ftell(in) );

   fclose( in );

Here we also open the file, seek to the end and ask the position, but use the file operations from the C standard library (which is included in the C++ standard library).

Note that the positions returned above may be the file size less one, as the start of the file (byte 1) is position 0, so byte_size_of_file should be incremented by one. Check the results with a file of known size. You can find the size of files in various ways: By DIR or ls commands, from a GUI file manager like Microsoft Windows Explorer etc.

To delete a file we have the C library function remove:

   #include <cstdio>

   // ...

   int status( remove("file/path/name") );

The returned status is zero if all went well or non-zero otherwise.

However in your case you are re-creating the file, so all you need to do is open it for writing with truncation (empties file). That is if the file exists all its previous data are removed so the file contains nothing. We can do this easily enough in both C and C++. In C++ we just open a std::ofstream:


   #include <fstream>

   // ...

   std::ofstream out( "file/path/name" );

Using the C library fopen function we would use the "w" mode string:

   #include <cstdio>

   // ...

   FILE * out( fopen("file/path/name", "w") );

Now various libraries probably have some support for such operations are you require. One such is the Boost (http://www.boost.org/) filesystem library (http://www.boost.org/libs/filesystem/doc/index.htm).

This library, with some modification, is being proposed for inclusion into the TR2 (Technical Report 2) update to the C++ standard library, so maybe one day we will have a decent C++ way to approach such problems. Of particular interest is the non-member operational function file_size:

   uintmax_t byte_size_of_file( file_size("file/path/name") );

This has been a brief trip around these topics. You should look up the reference material for the details such as meanings of returned values. All code snippets have been typed directly into the answer. Therefore they may contain omissions, typos or errors. Sorry if this is the case. They also contain no error checking - make sure your code _does_ check that all operations and function calls are successful and take appropriate action if they are not.

Hope this has been useful, and happy programming.  

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

©2016 About.com. All rights reserved.