_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 允许读取和写入。

当给定这两个常量时,将使用按位 or 运算符 (|) 连接它们。 如果未授予写入权限,则该文件为只读。 注意,所有文件始终具有可读性;不能提供只写权限。 因此,模式 _S_IWRITE_S_IREAD | _S_IWRITE 是等效的。

_wchmod_chmod的宽字符版本; filename_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 函数