-1

我使用打开一个文件,

    std::ifstream ifs(filename);

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

4

3 回答 3

4
ifs.close();
ifs.open(newfilename);
于 2012-10-20T16:56:53.823 回答
2

请考虑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();
于 2013-03-14T11:49:53.713 回答
0
       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
于 2012-10-20T17:02:12.053 回答