Share via


_chmod, _wchmod

變更檔案權限設定。

語法

int _chmod( const char *filename, int pmode );
int _wchmod( const wchar_t *filename, int pmode );

參數

filename
現有檔案的名稱。

pmode
檔案的權限設定。

傳回值

如果成功變更權限設定,則這些函式會傳回 0。 -1 的傳回值表示失敗。 如果找不到指定的檔案, errno 則會設定為 ENOENT ;如果參數無效, errno 則會設定為 EINVAL

備註

_chmod 式會變更 所 filename 指定檔案的許可權設定。 權限設定會控制檔案的讀取和寫入權。 整數運算式 pmode 包含 SYS\Stat.h 中所定義的下列其中一或兩個資訊清單常數。

pmode 意義
_S_IREAD 只允許讀取。
_S_IWRITE 允許寫入。 (實際上允許讀取和寫入)。
_S_IREAD | _S_IWRITE 允許讀取和寫入。

提供這兩個常數時,它們會與位或運算子聯結。 | 如果未指定寫入權限,則檔案是唯讀的。 請注意,所有檔案一律可讀取;無法授與唯寫許可權。 因此,_S_IWRITE_S_IREAD | _S_IWRITE 模式相同。

_wchmod 是寬字元版本的 _chmodfilename_wchmod 引數是寬字元字串。 否則,_wchmod_chmod 的行為即會相同。

這個函式會驗證它的參數。 如果 pmode 不是其中一個資訊清單常數的組合,或併入一組替代的常數,則函式只會忽略它們。 如果 filenameNULL ,則會叫用不正確參數處理常式,如參數驗證 中所述 。 如果允許繼續執行, errno 會設定為 EINVAL ,且此函式會傳回 -1。

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

泛型文字常式對應

Tchar.h 常式 _UNICODE_MBCS 未定義 _MBCS 定義 _UNICODE 定義
_tchmod _chmod _chmod _wchmod

需求

常式 必要的標頭 選擇性標頭
_chmod <io.h> <sys/types.h > 、 < sys/stat.h、 < errno.h >>
_wchmod <io.h > 或 < wchar.h> <sys/types.h > 、 < sys/stat.h、 < errno.h >>

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

範例

// crt_chmod.c
// This program uses _chmod to
// change the mode of a file to read-only.
// It then attempts to modify the file.
//

#include <sys/types.h>
#include <sys/stat.h>
#include <io.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>

// Change the mode and report error or success
void set_mode_and_report(char * filename, int mask)
{
   // Check for failure
   if( _chmod( filename, mask ) == -1 )
   {
      // Determine cause of failure and report.
      switch (errno)
      {
         case EINVAL:
            fprintf( stderr, "Invalid parameter to chmod.\n");
            break;
         case ENOENT:
            fprintf( stderr, "File %s not found\n", filename );
            break;
         default:
            // Should never be reached
            fprintf( stderr, "Unexpected error in chmod.\n" );
       }
   }
   else
   {
      if (mask == _S_IREAD)
        printf( "Mode set to read-only\n" );
      else if (mask & _S_IWRITE)
        printf( "Mode set to read/write\n" );
   }
   fflush(stderr);
}

int main( void )
{
   // Create or append to a file.
   system( "echo /* End of file */ >> crt_chmod.c_input" );

   // Set file mode to read-only:
   set_mode_and_report("crt_chmod.c_input ", _S_IREAD );

   system( "echo /* End of file */ >> crt_chmod.c_input " );

   // Change back to read/write:
   set_mode_and_report("crt_chmod.c_input ", _S_IWRITE );

   system( "echo /* End of file */ >> crt_chmod.c_input " );
}

A line of text.

      A line of text.Mode set to read-only
Access is denied.
Mode set to read/write

另請參閱

檔案處理
_access, _waccess
_creat, _wcreat
_fstat, _fstat32, _fstat64, _fstati64, _fstat32i64, _fstat64i32
_open, _wopen
_stat_wstat 函式