Setting the length of a file

O

Old Wolf

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.
 
D

Darren Cubitt

Old said:
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.

This almost certainly isn't portable - I'm not interested enough to find
out - but in MSVC at least (and it appears Digital Mars also, from a
quick Google), you can #include <io.h> and use these functions.

_fileno(FILE * stream) - returns the file descriptor of an open stream.

_chsize(int fd, long size) - changes the size of an open file, given a
file descriptor.

You will need to do some #ifdef magic to make this (relatively)
portable. __MSVC_VER__ will tell you if you're using MSVC. Not sure
about Digital Mars.
 
D

Darren Cubitt

And just a quick addendum... I have no idea if this will work with a
read-only file.

<io.h> also declares _chmod which allows you to change permissions on a
file. The _fstat group of functions will allow you to determine what the
previous permissions were, if you want to be nice to other people who
might use your code and restore them afterwards.
 
J

JosephKK

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,433
Messages
2,571,683
Members
48,796
Latest member
Greg L.

Latest Threads

Top