Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
306 views
in Technique[技术] by (71.8m points)

c - How do I insert and delete some characters in the middle of a file?

I want to insert and delete some chars in the middle of a file.

fopen() and fdopen() just allow to append at the end.

Is there any simple method or existing library that allow these actions?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As others have already told you, you have to do it manually, and use fseek in order to get to the place in which you have to insert or add characters. You can easily add new characters in the middle by doing the following:

  1. Go to the last byte of the file, and store the old file size of the file.
  2. Go to where you want to insert the new characters (say this is position): fread (old file size - position) bytes, and store them in a buffer.
  3. fseek to position again.
  4. fwrite your new characters.
  5. fwrite the buffer you previously read.

If you want to delete characters in the middle, then this is more tricky. Actually you cannot make a file shorter. You have two possibilities: in the first one, you just

  1. open the file and read the file skipping the characters you want to delete and store them in a buffer
  2. Close and re-open the file again with "b", so its contents is erased,
  3. Write the buffer and close the file.

In the second possibility, you:

  1. Read to a buffer the characters ahead of the ones you want to delete.
  2. fseek to the beginning of the characters you want to delete
  3. fwrite the buffer.
  4. Trim the rest of the file.

Point four is "tricky", because there is no standard (portable) way to do this. One possiblity is to use the operating system system calls in order to truncate the file. Another, simpler possibility is to just fwrite EOF in point 4. The file will be probably larger than it should be, but it will do the trick.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...