File truncating

01 May 2011

Is there a function inside the mbed library to truncate files? Normally, its called ftruncate but the compiler cannot find that.

Thanks in advance.

01 May 2011

I don't see anything in the mbed file related headers or in the ARM C/C++ library documentation that indicates that a file can be truncated other than completely deleting the contents of a file when it is opened for write.

What are you trying to accomplish with the truncation? Maybe there is another way to solve the problem without requiring the file to actually be truncated?

01 May 2011
  1. Open file for reading, read its contents into a buffer.
  2. Close and reopen file with "w".
  3. Write the saved content.
01 May 2011

If the data won't fit into a memory buffer then you can copy the contents a bit at a time into a new/smaller file, once the copy is completed delete the old file, and rename the new file to match the name of the original. Requires more storage.

It might be possible to just not require file truncation depending on what you are trying to accomplish. Some other ideas that come to mind:

  1. Have a file header that indicates the actual size of the file's data to indicate to the reader of the data that the excess data should be ignored
  2. If the file is text, fill in the excess data with spaces, newlines, or other convenient character.
02 May 2011

Thanks for all the replies.

Adam Green wrote:

What are you trying to accomplish with the truncation? Maybe there is another way to solve the problem without requiring the file to actually be truncated?

I've written a lightweight database engine which creates tables, inserts/updates/deletes records and searches the table. The idea is that if records at the end get deleted, the file size gets smaller.

I have come up with a solution to this problem based on your suggestions. It now doesnt resize the file but will attempt to recycle previously deleted records when a record is created. I also added a compact function which when called, it re creates the table and copies all the data over and removes any un used space.

And again, a big thanks to both of you for your replies. Your help was very useful.

03 May 2011

That is a pretty cool project and your solution sounds great.