gtpc2m3hC/C++ Language Support User's Guide

ftruncate-Truncate a File

This function truncates a file.

Format

#include <unistd.h>
int ftruncate(int fildes, off_t length);

fildes
An open file descriptor for the file whose size will be changed.

length
The new size of the file.

This function truncates the file indicated by the open file descriptor, fildes, to the indicated length. fildes must be a regular file or character special file that is open for writing. If the file size exceeds length, any extra data is discarded. If the file size is smaller than length, bytes between the old and new lengths are read as zeros. A change to the size of the file has no impact on the file offset.

TPF deviation from POSIX

The TPF system updates the st_mtime field only when the file is closed. The TPF system does not support the ctime time stamp.

If the ftruncate function is not successful, the file is not changed.

Normal Return

If successful, the ftruncate function returns a 0 value.

Error Return

If unsuccessful, the ftruncate function returns -1 and sets errno to one of the following:

EBADF
fildes is not a valid open file descriptor.

EINVAL
fildes does not refer to a regular file or character special file, it is opened as read-only, or the length specified is incorrect.

Programming Considerations

Examples

The following example shows one use of the ftruncate function.

#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
 
#define string_len 1000
 
main() {
  char *mega_string;
  int  fd, ret;
  char fn[]="write.file";
  struct stat st;
 
  if ((mega_string = malloc(string_len)) == NULL)
    perror("malloc() error");
  else if ((fd = creat(fn, S_IWUSR)) < 0)
    perror("creat() error");
  else {
    memset(mega_string, '0', string_len);
    if ((ret = write(fd, mega_string, string_len)) == -1)
      perror("write() error");
    else {
      printf("write() wrote %d bytes\n", ret);
      fstat(fd, &st);
      printf("the file has %ld bytes\n", (long) st.st_size);
      if (ftruncate(fd, 1) != 0)
        perror("ftruncate() error");
      else {
        fstat(fd, &st);
        printf("the file has %ld bytes\n", (long) st.st_size);
      }
    }
    close(fd);
    unlink(fn);
  }
}

Output

write() wrote 1000 bytes
the file has 1000 bytes
the file has 1 bytes

Related Information

open-Open a File.

See Appendix E, Programming Support for the TPF File System for more information about TPF File System C Functions.