You are here:

C++/changing the name of a text file .


hi sir,

thank you very much for your help,

my problem now , i want to open many existd  text files in my code and those file may have the following names 1.txt , 2.txt...........500.txt.

i want to open each file in its turn by using for loop.

for example

instream infile("x.txt")
infile >> n1

and so on


what i need that this loop should open the files according to the loop so  we will open file 1 ,2 till 500.
but here it is clear that it would not and it will open x.txt .

so can you please till me how can i do that by usng the loop


First I shall point out that the subject line is misleading. Changing the name of a text file sounds like you wish to change the name in the file system (like a rename, mv or ren operation from a shell or command prompt). In fact all that you need to do is to create the name from the value of the loop variable, which is in fact just changing the text of the string passed to the open operation to select a different file to open.

Now let me go into why your attempt failed. When you place something in double quotes in C and C++ it is interpreted as a string literal. This is data. It has no connection to the code, so when you say:


The x in that string has absolutely no connection to the x you are using in your code.

In order to change the name of what is opened we have to relate the string to the loop variable value. One way would be to have a long array of file name strings:

   char * filenamess[] = { "1.txt"
         , "2.txt"

         // , ...

         , "500.txt"

Then use this array in the for-loop:

   int n1;
   for( int x=0; x < 500; ++x )
       ifstream infile( files[x] );
       infile >> n1;

   // and so on...

Here we use the loop variable (now starting from 0) as the index into the files array to select the file name we want. Note that your original loop would not have attempted to open file 500.txt as you only continued while x is less than 500 (so 499.txt would be the last file you were attempting to open). I have also corrected the syntax you used for your loop and associated statements.

A more convenient option would be to build the file name string using the loop variable each time around. This of course is possible using string operations, but we need to convert the integer value that x has to a string equivalent. The facilities provided by C++ for doing this sort of thing are string streams. These are streams that have a similar usage interface to other streams like the file streams you are using. However, unlike the file streams the data read from or written to string streams are string objects in memory rather than files on disk. In this case we would want to write the number given by the value of x to a string stream. As we are writing a value, this will be an ostringstream (or more accurately a std::ostringstream):

   ostringstream os;

   int n1;
   for( int x=1; x <= 500; ++x )
   // write value of x to ostringstream then append .txt
       os << x << ".txt";
       ifstream infile( os.str().c_str() );
       os.seekp(0);       // Rewind os so we overwrite value next time
       infile >> n1;

   // and so on...

As you can see we can use the usual ostream insertion operators (operator<<) to write data to the string. Just as when using a file stream this data will be converted to text where required, as in the case of the integer value of x. The string data is held in a buffer and to access this we call the ostringstream::str() member function. This returns the buffer as a std::string. However, file streams take their filenames as a C style zero terminated array of char, so we have to call c_str() on this string before passing it to the ifstream constructor. After use I rewind the string stream object so we can overwrite it. If I did not do this then each new filename string making operation would append the new file name text to the existing text, which is not at all what is required!

To use the string streams include <sstream>.  


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


©2016 All rights reserved.