open with O_RDWR — how to overwrite?

感情迁移 提交于 2019-12-25 03:58:09

问题


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?


回答1:


You can use 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.




回答2:


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.



来源:https://stackoverflow.com/questions/7801315/open-with-o-rdwr-how-to-overwrite

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!