我使用
打开文件 std::ifstream ifs(filename);
我想使用相同的 ifs 变量打开一个新文件,我该怎么做?
答案 0 :(得分:4)
ifs.close();
ifs.open(newfilename);
答案 1 :(得分: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();
答案 2 :(得分: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