Re: Setting the length of a file
- From: Keith Thompson <kst-u@xxxxxxx>
- Date: Wed, 25 Mar 2009 00:04:34 -0700
"JosephKK"<quiettechblue@xxxxxxxxx> writes:
On Fri, 20 Mar 2009 00:32:30 -0700 (PDT), Old Wolf
<oldwolf@xxxxxxxxxxxxxx> wrote:
Is there any way to set the length of a file that
I've opened with fopen(filename, "r+b") ?
(I want to make the file shorter).
I want my code to work in both Unix and Windows;
in Unix there is a function ftruncate(); but I can't
find an equivalent function in either the C standard
or in my windows compiler.
I may be full of baloney or just thinking outside the box.
Open source file for read (rb) a temp file for write(wb), copy the
number of octets desired.
Close input file, delete input file, create new output file (wb) of
the same (path) name.
Reopen temp file (rb) and copy to output file.
Close both files.
Just might be portable.
Sure, but it could be extremely inefficient for large files, and it
could have undesirable side effects such as changing file metadata; it
can also fail if there's not enough room for a copy of the file. It's
very likely that both operating systems have system-specific methods
for truncating a file.
This is one of those tasks that can be done badly using pure standard
C, but much better using non-portable constructs.
Also, the steps of copying the temporary file back to the original
name can be accomplished using the standard C "rename" function.
Though rename() might be slow or impossible if, for examle, the two
files are not on the same filesystem -- and there's no completely
portable way to generate a name for the temporary file that's on the
same filesystem as the original.
--
Keith Thompson (The_Other_Keith) kst-u@xxxxxxx <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
.
- References:
- Setting the length of a file
- From: Old Wolf
- Re: Setting the length of a file
- From: JosephKK
- Setting the length of a file
- Prev by Date: Re: cooking the spaghetti
- Next by Date: Re: cooking the spaghetti
- Previous by thread: Re: Setting the length of a file
- Next by thread: What a magic??? Click the link given below and look what you have won.
- Index(es):
Relevant Pages
|