Linux environment Programming file I/O (vi): file properties

Source: Internet
Author: User
Tags lstat

Introduction:

When you use the ls-l filename command in Linux to view the properties of the filename, 9 Properties of the file are listed, for example: Ls-l/etc/fstab

-rw-r--r--1 root root 1102 2013-10-12 02:33/etc/fstab

from left to right are the types and permissions, the number of files, the owner of the file or directory, the group to which it belongs, the file size, the creation time, the file name

The information for these file attributes is stored in a stat structure. Here's an analysis of the structure.


To see the stat structure of a file, you can get it through the Stat class function!

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int stat (const char *path, struct stat *buf); The//stat function returns information about the command file that this path refers to.
int fstat (int fd, struct stat *buf); The//fstat function gets the information that has been opened on the file descriptor FD.
int Lstat (const char *path, struct stat *buf); The//lstat function is similar to stat, when a named file is a symbolic link, Lstat returns information about the symbolic link, rather than the information that references the file by the symbolic link.

The above three functions, if successful, returns 0, or 1 if an error occurs. The above three functions fill in a stat structure with buf points.

 struct stat {     dev_t St_dev;     /* ID of device containing file */ino_t St_ino;    /* inode number */mode_t st_mode;   /* Protection */nlink_t St_nlink;     /* Number of hard links */uid_t st_uid;     /* User ID of Owner */gid_t St_gid;    /* Group ID of Owner */dev_t St_rdev;    /* Device ID (if special file) */off_t st_size; /* Total size, in bytes */blksize_t st_blksize;  /* blocksize for file system I/O */blkcnt_t st_blocks;   /* Number of 512B blocks allocated */time_t st_atime;   /* Time of last access */time_t st_mtime;   /* Time of last modification */time_t st_ctime; /* Time of last status change * *}; 


A

File types, corresponding to the St_mode members in the stat structure, including ordinary files, directory files, block special files, character special files, FIFO (Named pipes), sockets, Symbolic Links 7 kinds of files . The file type information is included in the St_mode member of the stat structure. The macros in the following table are generally used to determine the file types, and the parameters of these macros are St_mode members in the stat structure .

Macro File type
S_isreg () Normal file
S_isdir () Catalog files
S_ISCHR () Character Special files
S_ISBLK () Block Special files
S_isfifo () Pipe or FIFO
S_islnk () Symbolic Links
S_issock () Sockets

Take macro S_isreg () as an example of how each of these macros is defined in <sys/stat.h>

# define S_IFMT__S_IFMT#DEFINES_ISREG (mode) __s_istype (mode), __s_ifreg #define__S_ISTYPE (Mode, mask) ((mode) & __S_IFMT) = = (mask))
Sample program:

/* *file name:typedemo.c *author    : libing *mail      : [email protected] *function  : Test the File type you input  */#include <sys/stat.h> #include <stdio.h> #include <stdlib.h>intmain (int argc, char *argv[]) { int   i;struct stat Buf;char    *ptr;for (i = 1; i < argc; i++) {printf ("%s:", Argv[i]); if (Lstat (argv[i), &buf) & Lt 0) {//Get STAT structure printf ("Lstat error.\n"); continue;}  //Use macros to test various file types if (S_isreg (Buf.st_mode)) printf ("regular"), if (S_isdir (Buf.st_mode)) printf ("directory"); (S_ISCHR (Buf.st_mode)) printf ("Character special"), if (S_isblk (Buf.st_mode)) printf ("Block Special"); if (S_isfifo ( Buf.st_mode)) printf ("FIFO"), if (S_islnk (Buf.st_mode)) printf ("Symbolic link"), if (S_issock (Buf.st_mode)) printf (" Sock ");p Utchar (' \ n ');} Exit (0);}
Program Test Results:

Compiler: GCC typedemo.c Execute program:./a.out/etc/fstab results show:/etc/fstab Regular


Two

Set User ID and set group ID: There are 6 IDs associated with a process, and the list is as follows:

Actual User ID who we actually are.
Actual Group ID
Valid user ID for file access
Valid group ID permission check
Additional Group ID
Saved settings User ID by the EXEC function
Saved settings Group ID is saved
Each file has an owner and group owner, and the owner is represented by the St_uid member in the stat structure, and the group owner is represented by the St_gid member. When executing a program file, the valid user ID of the process is usually the actual user ID, and the valid group ID is usually the actual group ID. However, you can set the two-bit special flag in the file mode Word (St_mode), the two bits in the file mode word are called set the user ID bit and set the group ID bit. These two-bit constants can be s_isuid and S_isgid tested.

Three

File access permissions, not just ordinary files, all file types have access rights. Each file has 9 access rights , as shown in table 1 below:

St_mode Shielding Significance
S_irusr
S_iwusr
S_ixusr
User-Read
User-Write
User-execution
S_irgrp
S_iwgrp
S_ixgrp
Group-Read
Group-Write
Group-Execution
S_iroth
S_iwoth
S_ixoth
Other-read
Other-write
Other-execution
Sample program:

/* * File NAME:PERMDEMO.C * author:libing * Mail: [email protected] * Function:test the file permation you Input */#include <stdio.h> #include <stdlib.h> #include <sys/stat.h> #include <sys/types.h>int Main (int argc, char *argv[]) {if (argc! = 2) {printf ("Usage:%s filename.\n", argv[0]); exit (0);} printf ("FileName:%s.\n", argv[1]), struct stat buf;if (Lstat (argv[1], &buf) = =-1) {printf ("stat error.\n"); exit (0);} Char perm[9] = {0};strcpy (perm, "---------"); mode_t mode = buf.st_mode;if (Mode & s_irusr) perm[0] = ' R '; if (Mode & S_IWUSR) Perm[1] = ' W ', if (Mode & S_IXUSR) perm[2] = ' x ', if (Mode & S_IRGRP) perm[3] = ' R '; if (mode & S_IWGRP) PE RM[4] = ' W '; if (mode & S_IXGRP) perm[5] = ' x '; if (mode & S_iroth) perm[6] = ' R '; if (mode & S_iwoth) perm[7] = ' W ' if (Mode & S_ixoth) perm[8] = ' x ';p rintf ("File Permission bits =%s.\n", perm);}
To compile the program test:

Compiler: GCC permdemo.c Execute program:./a.out/etc/fstab display Result: FileName:/etc/fstab. File permission bits = Rw-r--r--.

Four

Ownership of new files and directories: The user ID of the new file is set to a valid user ID for the process. The group ID of the new file can be a valid group ID for the process, or it can be the group ID of the directory in which it resides.

Five

Access functions are tested by the actual user ID and the actual group ID. Note the comparison with the valid User ID Access test in (iii).

#include <unistd.h>
int access (const char *pathname, int mode); Returns 0 if successful, or 1 if an error occurs.

The parameter mode is defined in the <unistd.h> file, as shown in table 2 below:

Mode Description
R_ok
W_ok
X_ok
F_ok
Test Read Permissions
Test Write permissions
Test Execution permissions
Test whether the file exists
Example code:

#include <fcntl.h> #include <stdio.h> #include <stdlib.h>intmain (int argc, char *argv[]) {if (argc! = 2) printf ("Usage:a.out pathname"); if (Access (argv[1], R_OK) < 0) printf ("Access error for%s", argv[1]); elseprintf ("Read Ok.\n "), if (open (argv[1], o_rdonly) < 0) printf (" Open error for%s ", argv[1]); elseprintf (" Open for reading ok\n "); Exit ( 0);}
Program test:

Compiler: GCC access.c Execute program:./a.out/etc/fstab display Result: Read Ok.open for reading OK
Six

The Umask function creates a mask word for the process settings file mode and returns the previous value.
#include <sys/types.h>
#include <sys/stat.h>
mode_t umask (mode_t mask); Return to previous file mode create a mask word

The parameter cmask is composed of several bitwise "or" in the 9 constants listed in table 1 above. The corresponding bit in file mode must be turned off for any bit that is 1 in the File Pattern creation screen Word.

Sample program:

/* *file name:umaskdemo.c *author    : libing *mail      : [email protected] *function  : Just the umask Function */# Include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <sys/stat.h> #define RWRWRW (S _IRUSR | S_IWUSR | S_irgrp | S_iwgrp | S_iroth | S_iwoth) Intmain (void) {umask (0);   Set file Mode Create mask if (creat ("foo", RWRWRW) < 0) printf ("Create foo  error.\n"); Umask (S_irgrp | S_iwgrp | S_iroth | S_iwoth);  Set the file mode to create the mask if (creat ("Far", RWRWRW) < 0) printf ("Create far error.\n"); exit (0);}
Program tests show:

Compiler: GCC UMASK.C executes the program:./a.out test shows: ls-l far foo-rw-------1 book book 0 2014-05-12 20:40 far-rw-rw-rw-1 Book Book 0 2014- 05-12 20:40 foo

Seven

the chmod function and the Fchmod function can change the access rights of an existing file. The Chmod function operates on the specified file, while the FCHMOD function operates on the file that is already open.

#include <sys/stat.h>
int chmod (const char *path, mode_t mode);
int fchmod (int fd, mode_t mode);


In addition: The St_size member in the stat struct represents the length of the file in bytes.






Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.