我正在尝试从文件中删除一行而不创建一个新文件。例如,在修改之前的文件中,它将是:
This
is
a
file
然后是:
This
a
file
但是,以我目前尝试的方式,发生的事情是
This
a
file
我知道我可以做到的,方法是只将我想要的内容写入另一个文件,然后重命名该文件并删除旧文件,但是我想知道除此之外是否还有其他方法。
我尝试使用
if (string::npos != line.find(SPSID))
{
iPos = (pos - line.size() - 2);
stream.seekg(iPos);
for (int i = (pos - line.size() - 2); i < pos; i++)
{
//Sets input position to the beginning of the current line and replaces it with NULL
stream.put(0);
}
stream.seekp(iPos);
pos = stream.tellp();
}
,以及将stream.put(0);
替换为stream.write(nullLine, iPos);
但两者都没有。
int Delete(string fileName, string SPSID)
{
//Variables
string line;
char input[MAX_CHAR];
fstream stream;
streamoff pos = 0;
streamoff iPos = 0;
//Opening and confirming opened
stream.open(fileName);
if (!stream.is_open())
{
cout << "File Did not open.\n" << endl;
return -1;
}
//Loops until the end of the file
do
{
//Gets one line from the file and converts it to c++ string
stream.getline(input, MAX_CHAR, '\n');
line.assign(input);
//Finds the current output position (which is the start of the next line)
pos = stream.tellp();
//Finds and checks if the SPSID is in the string. If it is then print to screen otherwise do nothing
if (string::npos != line.find(SPSID))
{
iPos = (pos - line.size() - 2);
stream.seekg(iPos);
for (int i = (pos - line.size() - 2); i < pos; i++)
{
//Sets input position to the begining of the current line and replaces it with ""
stream.put(0);
}
stream.seekp(iPos);
pos = stream.tellp();
}
} while (stream.eof() == false); //Checks that the end of the file has not been reached
stream << "Test" << endl;
//Resets the input and output positions to the begining of the stream
stream.seekg(0, stream.beg);
stream.seekp(0, stream.beg);
//Closing and Confirming closed
stream.close();
if (stream.is_open())
{
cout << "File did not close.\n" << endl;
return -2;
}
return 0;
}
我可能必须制作一个新文件并重命名它,但认为仍然值得询问这是否可行。 :/