使用std :: ifstream的
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
这有几个问题,包括使用'char *'代替'std :: string',不释放'char *',不打开另一个文件(这是个问题),并且使用while(!ifs.eof())而不是'while(ifs >>) )'。还有一些不必要的事情。 – chris
这是C还是C++? –
你不应该在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();
你自己说:'ifs.open()'。 – chris
如何给一个新的文件名? – rajat
@rajat - 'ifs.open(newfilename)' – Benj