c++ - 从文件中删除一行而不创建新文件
问题描述
我正在尝试从文件中删除一行而不创建新文件。例如,在修改之前的文件中,它将是:
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;
}
我可能不得不制作一个新文件并重命名它,但我认为这仍然值得询问这是否可能。:/
解决方案
推荐阅读
- python - 嵌入图像问题
- electron - 在 Electron 中写入打包的应用程序文件夹
- javascript - 将选定数据从一个页面传递到 html 中的另一页面
- arangodb - 尝试连接到 LAN 上的 ArangoDB 服务器时,“请求的地址在其上下文中无效”
- javascript - 如何在 async.waterfall 中的 promise().then() 中调用 cb()
- java - 是否可以/有必要更改 Java 中的垃圾收集间隔
- php - 从用户给出的字符串中获取日期时间对象
- azure - 黑白差异 Get-AzureAutomationConnection VS Get-AzureRMAutomationConnection?
- javascript - Http Angular JS 花了很长时间才得到响应
- ffmpeg - FFmpeg 缩放和 concat 与动态高度