Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

File truncation method for Python

7 views
Skip to first unread message

Jim Roskind

unread,
Dec 6, 1994, 9:13:03 PM12/6/94
to
I wrote code to supply a truncation method for the builtin class of
file objects. Even though there was a post about how to make such a
piece of functionality more portable, I've just supplied the basic
implementation in this patch. [Note that the comment supplied about
portability indicated that ftruncate() takes a file handle, which is
not true (for at least some platforms), and so I didn't trust the
remainder of the info.]

For the record the method is called "truncate", and it works on a file
handle. It takes an optional argument, which specifies the size of the
truncated file. If no argument is provided, it truncates to the
current position of the file pointer. Note that since the underlying
ftruncate operates on a file descriptor (believe it or not), it was
necessary to fflush() the stream before performing the truncate. I
thought about doing a seek() as well, but could not find compelling
reason to move the stream pointer.

cut here--------------------------------------------------------
*** fileobject.c.org Mon Aug 1 04:33:16 1994
--- fileobject.c Tue Dec 6 17:41:06 1994
***************
*** 232,237 ****
--- 232,280 ----
}

static object *
+ file_truncate(f, args)
+ fileobject *f;
+ object *args;
+ {
+ long newsize;
+ int ret;
+
+ if (f->f_fp == NULL)
+ return err_closed();
+ if (!getargs(args, "l", &newsize)) {
+ err_clear();
+ if (!getnoarg(args))
+ return NULL;
+ BGN_SAVE
+ errno = 0;
+ newsize = ftell(f->f_fp); /* default to current position*/
+ END_SAVE
+ if (newsize == -1L) {
+ err_errno(IOError);
+ clearerr(f->f_fp);
+ return NULL;
+ }
+ }
+ BGN_SAVE
+ errno = 0;
+ ret = fflush(f->f_fp);
+ END_SAVE
+ if (ret == 0) {
+ BGN_SAVE
+ errno = 0;
+ ret = ftruncate(fileno(f->f_fp), newsize);
+ END_SAVE
+ }
+ if (ret != 0) {
+ err_errno(IOError);
+ clearerr(f->f_fp);
+ return NULL;
+ }
+ INCREF(None);
+ return None;
+ }
+
+ static object *
file_tell(f, args)
fileobject *f;
object *args;
***************
*** 615,620 ****
--- 658,664 ----
{"readline", (method)file_readline},
{"readlines", (method)file_readlines},
{"seek", (method)file_seek},
+ {"truncate", (method)file_truncate},
{"tell", (method)file_tell},
{"write", (method)file_write},
{"writelines", (method)file_writelines},
cut here--------------------------------------------------------

Jim

--
Jim Roskind
voice: 408.982.4469
fax: 408.986.1889
j...@infoseek.com
----------------------------------------------------------------------------
PGP 2.6.1 Key fingerprint = 0E 2A B2 35 01 9B 5C 58 2D 52 05 9A 3D 9B 84 DB
To get my PGP 2.6 Public Key, "finger -l j...@infoseek.com | pgp -kaf"

0 new messages