Chapter Contents

Previous

Next
ftruncate

ftruncate



Truncate a File

Portability: POSIX.1 conforming


SYNOPSIS
DESCRIPTION
RETURN VALUE
IMPLEMENTATION
EXAMPLE
SEE ALSO


SYNOPSIS

#include <unistd.h>

int ftruncate(int fn, off_t length);


DESCRIPTION

ftruncate truncates an USS file open for write access to length in bytes. fn is the file descriptor for the file to be truncated. ftruncate does not change the current file position.


RETURN VALUE

ftruncate returns a 0 if it is successful and a -1 if it is not successful.


IMPLEMENTATION

Data beyond the end of the truncated file are lost. If the file size is smaller than the specified length , the file is unchanged.


EXAMPLE

#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>

main()
{
   FILE *testfile;
   int fd, long size;
   char flname[] ="trunc.test";

   if ((fd=creat(flname,S_IRUSR1)) < 0)
      perror("creat() error");
   else {
      if ((testfile = fdopen(fd, "w")) == NULL) {
         perror("fdopen() error");
         close(fd);
      }
   }
   fputs("ABCDEFGHIJKLMNOPQRSTUVWXYZ",testfile);
   fflush(testfile);
   size = lseek(fd, 0, SEEK_END);
   printf("The file is %ld bytes long.\n", size);

   if (ftruncate(fd, 3) !=0)
      perror("ftruncate() error");
   else {
      size = lseek(fd, 0, SEEK_END);
      printf("The file is now %ld bytes long.\n", size);
   }
fclose(testfile);
unlink(flname);
}


SEE ALSO


Chapter Contents

Previous

Next

Top of Page

Copyright © 2001 by SAS Institute Inc., Cary, NC, USA. All rights reserved.