用O_RDWR打开——如何覆盖?
我想读取一个文件并更改其内容并将其写回到文件中。
我使用 open
来读取文件,如下所示:
bfd = open(m_file_name.c_str(), O_RDWR)
但是当我写入时,它有点将其附加到旧文件中。我怎样才能覆盖它?
I want to read a file and change its content and write it back to the file.
I use open
to read a file as follows:
bfd = open(m_file_name.c_str(), O_RDWR)
But when I write, it is kinda append it to the old one. How can I overwrite it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
lseek(2)
如果您的文件现在的大小小于原始文件的大小,则需要将大小截断为新的大小,否则您将保留旧末尾的字节文件在最后。如果文件较大,则文件应在您写入时自动增长。
You can use
lseek(2)
If your file is now less in size than the original, you will need to truncate the size to the new size, or you'll leave the bytes from the old end of the file at the end. If it's larger, the file should grow automatically as you write.
如果您想在特定位置写入,则必须使用
lseek
进行查找。您不会尝试覆盖整个文件,对吗?只是其中的一小部分吗?如果您试图覆盖整个文件,那么这是一个不好的方法。
You have to seek with
lseek
if you want to write at a specific position.You are not trying to overwrite the entire file, right? Just a small part of it? If you are trying to overwrite the entire file then this is a bad way to do it.