this is a simple code i used to delete autorun.inf file that mostly used by virus n replace it become an icon to my thumb drive. it work for autorun.inf which having attrib of hidden but not read-only..how can i use infile.open to acess a read-only file?

     fstream infile;
     fstream outfile;
     cout<<"file detected"<<endl;
     system("del /f /a:- autorun.inf");

     cout<<"autorun file not found\n";
     //cout<<"creating a new autorun file...\n";

    system("attrib +h autorun.inf");*/
     return 0;

std::ios::trunc is default for std::ios::out and therefore std::ofstream
objects and not std::ios::in and std::ifstream objects as originally stated.

Apologies for the error and any confusion it caused.

Text corrected below (lines prefixed with '>').

There should be no reason not to be able to open a read only file for just reading (i.e. input). However you have used a std::fstream (which defaults to opening a file for reading and writing, truncating it if it exists), not a std::ifstream (which defaults to opening files for reading, truncating it if it exists). That is:

   std::fstream infile;

Is equivalent to :

   std::fstream infile;
   infile.open("autorun.inf", std::ios::in | std::ios::out | std::ios::trunc);


   std::ifstream infile;          // note: ifstream _not_ fstream

Is equivalent to :

   std::ifstream infile;          // note: ifstream _not_ fstream
>   infile.open("autorun.inf", std::ios::in); // note; _no_ std::ios::out | std::ios::trunc


   std::ofstream outfile;          // note: ofstream _not_ fstream

Is equivalent to :

   std::ofstream outfile;          // note: ofstream _not_ fstream
>    outfile.open("autorun.inf", std::ios::out | std::ios::trunc);  // note; _no_ std::ios::in

> or:

>    outfile.open("autorun.inf", std::ios::out );  // note; _no_ std::ios::in

> As std::ios::out implies std::ios::trunc by default.

So unless you require a file open for read and writing at the same time use the variant for either reading or writing as appropriate, or explicitly specify the exact combination of open mode flags you require.

Note also that you can open a file during construction of a file stream object:

   std::ifstream infile("autorun.inf");

You can check for a file being open using the is_open member function and that open files are closed when file stream objects are destroyed (although not too useful in this case).

Please note that main function returns an int and in C++ we must specify this, unlike C where no specified return type implies int. Also for main and main only if no return value is given return 0 is assumed, although some broken compilers - e.g. MSVC++ 6 and earlier - do not allow this behaviour.

I would then re-work your program something like so (for starters):

   #include <fstream>      // for std::ifstream, std::ofstream
   #include <iostream>     // for std::cout
   #include <string>       // for std::string
   #include <cstdlib>      // for system

   int main()
       char const * filepath("autorun.inf");
       std::ifstream infile( filepath );

       if ( infile.is_open() )
         std::cout << filepath << " file detected, deleting..." << std::endl;
         std::string delete_cmd( "del /f /a:- " );
         delete_cmd += filepath;
         system( delete_cmd.c_str() );
         std::cout << filepath << " file not found." << std::endl;

       std::ofstream outfile( filepath );
       if ( outfile.is_open() )
         std::cout   << "creating a new " << filepath << " file..."
         << std::endl
         outfile << "[autorun]\n"
         << "icon=icon\\cl.ico\n"
         std::string attrib_cmd( "attrib +h " );
         attrib_cmd += filepath;
         system( attrib_cmd.c_str() );


I have extracted the common file name out into a (constant) string literal. This should make it easier if you wish to extend the program - e.g. making the logic a function and passing filepath to the function - having maybe added command line argument processing to allow entry of the drive to check for an autorun.inf file. This has the effect of requiring the commands passed to the system function to be built from the command part and the file path part. The easiest way to do this is to use a standard C++ library string (std::string) - see the delete_cmd and attrib_cmd. This implies you have a reasonably up to date compiler and C++ standard library implementation (For Microsoft compilers, say MSVC++ 6 or later, maybe even MSVC++ 5 - I cannot remember that far back!).

The program now uses std::ifstream and std::ofstream file stream objects as appropriate, declaring/defining them as needed and specifying the file to open as constructor arguments. Both streams are now checked to ensure the file is open before being used. I have not added any additional error reporting to the outfile case however - I shall leave that to you.

I regularised the use of std::endl versus '\n'. I use std::endl for output to the console (although not usually required) and '\n' when writing to outfile - as this stream will be flushed when the file is closed anyway (std::endl writes '\n' to the stream and then flushes it).

I gave the program (including the now uncommented out part for re-creating the file) a quick test, building it using MSVC++ 2008.

Note you can also do what you wish using a batch file, maybe something like:

   @echo off
   set file=autorun.inf

   if not exist %file% goto write_autorun

   echo Removing existing %file%
   del /f /a:- %file%

   echo Creating new %file%
   echo [autorun] > %file%
   echo icon=icon\cl.ico >> %file%
   attrib +h %file%
   set file=

You can get help on batch file commands, like other Microsoft CMD command processor commands, using the help command (e.g. help command). Note I am assuming you are using MS Windows NT, 2000, XP, Vista and not 9x,ME or earlier (as I forget the details of command.com usage!)

Hope this helps.


All Answers

Answers by Expert:

Ask Experts


Ralph McArdell


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.


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/.


©2017 About.com. All rights reserved.