Truncate a file at a given position
#include <sys/types.h> #include <unistd.h> off_t ltrunc( int fildes, off_t offset, int whence );
libc
Use the -l c option to qcc to link against this library. This library is usually included automatically.
The ltrunc() function attempts to truncate the file at a specified position. The file, referenced by the open file descriptor fildes, must have been opened O_WRONLY or O_RDWR. The truncation point is calculated using the value of offset as a relative offset from a file position determined by the value of the argument whence. The value of offset may be negative, although a negative truncation point (one before the beginning of the file) is an error.
The calculated truncation point, if within the existing bounds of the file, determines the new file size; all data after the truncation point no longer exists. If the truncation point is past the existing end of file, the file size isn't changed. An error occurs if you attempt to truncate before the beginning of the file (that is, a negative truncation point).
The current seek position isn't changed by this function under any circumstance, including the case where the current seek position is beyond the truncation point. |
Upon successful completion, this function returns the new file size. If a truncation point beyond the existing end of file was specified, the existing file size is returned, and the file size remains unchanged. Otherwise, ltrunc() returns a value of -1 and sets errno to indicate the error. The file size remains unchanged in the event of an error.
#include <stdio.h> #include <fcntl.h> #include <sys/types.h> #include <unistd.h> char buffer[1000]; int main( void ) { int fd, stat; fd = open( "test", O_CREAT | O_RDWR, 0666 ); if( fd == -1 ) { fprintf( stderr, "Open error\n" ); exit( -1 ); } /* Create a 1000-byte file */ write( fd, buffer, 1000 ); /* Seek back to offset 500 and truncate the file */ if( ltrunc( fd, 500, SEEK_SET ) == -1 ) { fprintf( stderr, "ltrunc error\n" ); exit( -1 ); } close( fd ); fd = open( "test", O_CREAT | O_RDWR, 0666 ); printf( "File size = %ld\n", lseek( fd, 0, SEEK_END ) ); close( fd ); return 0; }
Safety: | |
---|---|
Cancellation point | Yes |
Interrupt handler | No |
Signal handler | No |
Thread | Yes |
The ltrunc() function isn't portable, and shouldn't be used in new code. Use ftruncate() instead.