与O_RDWR打开 - 如何改写? [英] open with O_RDWR -- how to overwrite?

查看:143
本文介绍了与O_RDWR打开 - 如何改写?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想读一个文件并更改其内容并把它写回文件。

I want to read a file and change its content and write it back to the file.

我用打开来读取文件如下:

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?

推荐答案

您可以使用 lseek的(2)

bfd = open(m_file_name.c_str(), O_RDWR);
// read your file
lseek(bfd, 0, SEEK_SET);
// do whatever manipulation & write file

如果您的文件的大小比原来的少,现在,你需要的大小截断新的大小,否则你会从最终文件的旧结束后离开的字节数。如果是较大的,该文件应为你写的自动增长。

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.

这篇关于与O_RDWR打开 - 如何改写?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆