Path: utzoo!attcan!uunet!lll-winken!lll-tis!ames!oliveb!sun!gorodish!guy From: guy@gorodish.Sun.COM (Guy Harris) Newsgroups: comp.unix.questions Subject: Re: Truncating an open file under BSD 4.3 Keywords: Empty, !ftruncate, fcntl? Message-ID: <61401@sun.uucp> Date: 26 Jul 88 07:14:07 GMT References: <1392@valhalla.ee.rochester.edu> Sender: news@sun.uucp Lines: 29 > What is the best way to empty an already open write-only file under BSD 4.3? If by "empty" you mean "reduce to zero length", use "ftruncate". > I tried truncate but it leaves holes in the file, which make > it unreadable. You must have done it wrong. Note that, even though "ftruncate(fd, 0L)" truncates the file to zero length, it does NOT move the seek pointer; thus, write(fd, lots of data, how much data); ... ftruncate(fd, 0L); write(fd, more data, how much more data); will NOT put the "more data" at the beginning of the file, but will put it at the same place it would have had the "ftruncate" not been done; this results in a hole of size equal to the size of the file before the "ftruncate". Do an "lseek(fd, 0L, 0)" after the "ftruncate". Note that if you're using standard I/O to write to the file, you probably have to "fflush" the file before doing the "ftruncate". > I also could not find a way with fcntl, which surprises me. Why? "fcntl" was originally intended to manipulate descriptors, not the objects they referred to; subsequently, "fcntl" has turned into something similar to "ioctl" but different (e.g., it's used for file locking - I'm not sure what the *intended* difference between "fcntl" and "ioctl" is), but nobody's made "fcntl" do file truncation - yet.