问题
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