We help IT Professionals succeed at work.

We've partnered with Certified Experts, Carl Webster and Richard Faulkner, to bring you a podcast all about Citrix Workspace, moving to the cloud, and analytics & intelligence. Episode 2 coming soon!Listen Now


How to truncate the file using C++ no MFC

riteshromi asked
Medium Priority
Last Modified: 2007-11-27
I want to truncate a file using c++. Tried moving the end of file but the data still present. Can someone please tell me how to truncate the file.
Watch Question

Top Expert 2005
Use truncate() or ftrunctate()

TRUNCATE(2)                 BSD System Calls Manual                TRUNCATE(2)

     truncate, ftruncate -- truncate or extend a file to a specified length

     #include <unistd.h>

     truncate(const char *path, off_t length);

     ftruncate(int fd, off_t length);

     Truncate() causes the file named by path or referenced by fd to be trun-
     cated or extended to length bytes in size.  If the file previously was
     larger than this size, the extra data is lost. If the file was smaller
     than this size, it will be extended as if by writing bytes with the value
     zero.  With ftruncate(), the file must be open for writing.

     A value of 0 is returned if the call succeeds.  If the call fails a -1 is
     returned, and the global variable errno specifies the error.

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts


thx for the solution. Just wanted to clarify, is this for unix or windows
would appreciate your response
Top Expert 2005

They appear to be Unix interfaces.  For Microsoft OS, use _chsize() or _chsize_s():

Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.


Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.