使用std :: ifstream的

问题描述:

我打开使用文件,使用std :: ifstream的

std::ifstream ifs(filename); 

我想打开使用相同IFS变量一个新的文件打开一个新的文件,我该怎么做呢?

+0

你自己说:'ifs.open()'。 – chris

+0

如何给一个新的文件名? – rajat

+0

@rajat - 'ifs.open(newfilename)' – Benj

ifs.close(); 
ifs.open(newfilename); 

 ifs.close();  //close the previous file that was open 
     ifs.open("NewFile.txt", std::ios::in); //opens the new file in read-only mode 

     if(!ifs)        //checks to see if the file was successfully opened 
     { 
      std::cout<<"Unable to read file...\n"; 
      return; 
     } 

     char* word = new char[SIZE]; //allocate whatever size you want to 
     while(ifs>>word)  
     { 
      //do whatever 
     } 
     ifs.close();   //close the new file 
     delete[] word;   //free the allocated memory 
+1

这有几个问题,包括使用'char *'代替'std :: string',不释放'char *',不打开另一个文件(这是个问题),并且使用while(!ifs.eof())而不是'while(ifs >>) )'。还有一些不必要的事情。 – chris

+0

这是C还是C++? –

+0

你不应该在C++代码中使用malloc。 – Borgleader

请考虑到std::ifstream.close()不清除它的标志, 可能包含从上次会话值。在与其他文件一起使用流之前,请始终使用clear()函数清除标志。

例子:

ifstream mystream; 
mystream.open("myfile"); 
while(mystream.good()) 
{ 
    // read the file content until EOF 
} 
mystream.clear(); // if you do not do it the EOF flag remains switched on! 
mystream.close(); 

mystream.open("my_another_file"); 
while(mystream.good()) // if not cleared, this loop will not start! 
{ 
    // read the file 
} 
mystream.close();