### _chsize -- Alter Length of File

Format

>     #include <io.h>
>     int _chsize(int handle, long size);

Language Level: Extension
_chsize lengthens or cuts off the file associated with handle to the length specified by size. You must open the file in a mode that permits writing. _chsize adds null characters (\0) when it lengthens the file. When _chsize cuts off the file, it erases all data from the end of the shortened file to the end of the original file.

Return Value
_chsize returns the value 0 if it successfully changes the file size. A return value of -1 shows an error; _chsize sets errno to one of the following values:

Value | Meaning
EACCESS | The specified file is locked against access.
EBADF | The file handle is not valid, or the file is not open for writing.
ENOSPC | There is no space left on the device.
EOS2ERR | The call to the operating system was not successful.

Example
This example opens a file named sample.dat and returns the current length of that file. It then alters the size of sample.dat and returns the new length of that file.

    #include <io.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <fcntl.h>

    int main(void)
    {
       long length;
       int fh;

       printf("\nCreating sample.dat.\n");
       system("echo Sample Program > sample.dat");
       if (-1 == (fh = open("sample.dat", O_RDWR|O_APPEND))) {
          printf("Unable to open sample.dat.\n");
          return EXIT_FAILURE;
       }
       if (-1 == (length = _filelength(fh))) {
          printf("Unable to determine length of sample.dat.\n");
          return EXIT_FAILURE;
       }
       printf("Current length of sample.dat is %d.\n", length);
       printf("Changing the length of sample.dat to 20.\n");
       if (-1 == (_chsize(fh, 20))) {
          perror("_chsize failed");
          return EXIT_FAILURE;
       }
       if (-1 == (length = _filelength(fh))) {
          printf("Unable to determine length of sample.dat.\n");
          return EXIT_FAILURE;
       }
       printf("New length of sample.dat is %d.\n", length);
       close(fh);
       return 0;

       /**********************************************************
          The output should be similar to:

          Creating sample.dat.
          Current length of sample.dat is 17.
          Changing the length of sample.dat to 20.
          New length of sample.dat is 20.
       **********************************************************/
    }

_filelength -- Determine File Length
lseek -- Move File Pointer
<io.h>