• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 637
  • Last Modified:

How to write EOF during "r+" file access w/ fprintf

Need to write EOF to get rid of the last few lines in a text file.

0
nepigid
Asked:
nepigid
  • 2
  • 2
1 Solution
 
nietodCommented:
Sorry standard C++ provides no features for truncating a file at a specific offset.  

The only way to do this within standard C++ is to open a file and truncate it and then write to it.  You can use the "w" or "w+" modes to do this.

However, most OSs have procedures for truncating files.  For example, in Windows you can use SetEndOfFile(). to set a file's length.
0
 
nepigidAuthor Commented:
Hi - thanks for the quick responce, however, I am a bit confused:

On one hand you say, "standard C++ provides no features for truncating a file" and then you say, "open a file and truncate it."

Could you clarify how to truncate in C?
0
 
nietodCommented:
You left out the importatn part of what I said "at a specific offset".   You have two choices--you can use truncate the file at its start and then write to it or you can open it as it is and write to it  (in this case you can make the file longer, but not shorter).

This is due to C's legacy, many types of storage devices, like punch card machines, would not provide a way to shorten a file.

So C does not allow you to truncat to a specific spot. If you need to shorten a file, you have to copy the contents that you want to keep to another location (like another file)  Then close and re-open the file and truncate it ("w" mode) and write the information back.

Or use an OS-specific method, like SetEndOfFile().
0
 
nepigidAuthor Commented:
Ok - that is what I had guessed.  The only way to shorten a file is to re-create the file.

However, I will leave this question open until next week to see if anyone else has input.

Thanks again.
0

Featured Post

[Webinar] Kill tickets & tabs using PowerShell

Are you tired of cycling through the same browser tabs everyday to close the same repetitive tickets? In this webinar JumpCloud will show how you can leverage RESTful APIs to build your own PowerShell modules to kill tickets & tabs using the PowerShell command Invoke-RestMethod.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now