共用方式為


_chsize

變更檔案大小。 有更安全的版本可供使用;請參閱 _chsize_s

語法

int _chsize(
   int fd,
   long size
);

參數

fd
參考已開啟檔案的檔案描述項。

size
檔案的新長度 (位元組)。

傳回值

如果已成功變更檔案大小,則 _chsize 會傳回值 0。 -1 的傳回值表示錯誤: errno 如果指定的檔案是唯讀的,或指定的檔案遭到鎖定而無法存取,則為 ;如果描述元無效、 EBADFENOSPC 裝置上沒有空格,或 EINVALsize 小於零,則設定 EACCES 為 。

如需傳回碼的詳細資訊,請參閱 errno_doserrno_sys_errlist_sys_nerr

備註

_chsize 函式會將與 fd 相關聯的檔案擴充或截斷至 size 所指定的長度。 檔案必須以允許寫入的模式開啟。 如果擴充檔案,則會附加 Null 字元 ('\0')。 如果檔案遭到截斷,則會遺失從縮短檔案結尾到檔案原始長度的所有資料。

這個函式會驗證它的參數。 如果 size 小於零或 fd 不是錯誤的檔案描述元,則會叫用不正確參數處理常式,如參數驗證 中所述

根據預設,此函式的全域狀態會限定于應用程式。 若要變更此行為,請參閱 CRT 中的全域狀態。

需求

常式 必要的標頭 選擇性標頭
_chsize <io.h> <errno.h>

如需相容性詳細資訊,請參閱相容性

範例

// crt_chsize.c
// This program uses _filelength to report the size
// of a file before and after modifying it with _chsize.

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

int main( void )
{
   int fh, result;
   unsigned int nbytes = BUFSIZ;

   // Open a file
   if( _sopen_s( &fh, "data", _O_RDWR | _O_CREAT, _SH_DENYNO,
                 _S_IREAD | _S_IWRITE ) == 0 )
   {
      printf( "File length before: %ld\n", _filelength( fh ) );
      if( ( result = _chsize( fh, 329678 ) ) == 0 )
         printf( "Size successfully changed\n" );
      else
         printf( "Problem in changing the size\n" );
      printf( "File length after:  %ld\n", _filelength( fh ) );
      _close( fh );
   }
}
File length before: 0
Size successfully changed
File length after:  329678

另請參閱

檔案處理
_close
_sopen, _wsopen
_open, _wopen