UNIX advanced environment programming (5) Files And Directories, unixdirectories

Source: Internet
Author: User

UNIX advanced environment programming (5) Files And Directories, unixdirectories

1 File Times

Each file maintains three time fields, each representing a different time field. See the following table:

Field description:

  • St_mtim (the modification time) records the last time the file content was modified.
  • St_ctim (the changed-status time) records the last time the I-node of the file was modified, such as modifying the File Permission bit and modifying the file owner ID, modify the number of links associated with the file.

The information in I-node is separated from the actual content of the file. Therefore, when I-node is updated, st_ctim (the changed-status time) must be updated ), instead of st_mtim (the modification time ).

The time standard used by the command ls to sort parameters:

  • Parameter-l and-t: Use st_mtim (the modification time of the file)
  • Parameter-u: Use st_atim (the last-access time of file)
  • Parameter-c: Use st_ctim (the last-change time of I-node status)

The following table summarizes some functions that will affect these three time periods. before you see the table, we need to understand:

  • A directory is a file that contains the Directory Index: the list of file names contained in the Directory and the number of associated I-nodes.
  • When you create, delete, or modify an index in a directory, three times of the Directory are updated.
  • For example, creating a new file will update the corresponding time in the directory containing the file, and the I-node of the file. Reading and writing a file only affects the Time of the file, but does not affect the directory containing the file.

 

2 futimens, utimensat, and utimes Functions

Function: modifies the access time and modification time of a file.

Function declaration:

#include <sys/stat.h>

int futimens(int fd, const struct timespec times[2]);

int utimensat(int fd ,const char *path, const struct timespec times[2], int flag);

Parameter description:

The strcut timespec struct contains at least two time fields: time_t TV _sec (seconds) and long TV _nsec (milliseconds ).

The array times contains two times: the first element is access time, and the second element is modification time.

Function behavior is affected by the value of the times parameter. You can query the function by reference.

 

At the same time, executing the above pair of functions also requires the permission as follows:

  • If the times parameter is a non-null pointer or the TV _nsec field is UTIME_NOW, the call to this function requires that the valid user ID of the process must be the ID of the file owner, or the process has the write permission on the file, or the process is an administrator (super user) process.
  • If the times parameter is a non-null pointer and the value of the TV _nsec field is not UTIME_NOW or UTIME_OMIT, the calling of this function requires that the valid user ID of the process must be equal to the owner ID of the file, or the process is an administrator process. Different from the above one, in this case, it is not enough to have write permissions on the file.
  • If the times parameter is a non-null pointer and the value of the TV _nsec field is UTIME_OMIT, no permission check is performed.

Function details:

  • The futimens function requires that the file be opened. The corresponding time of the file can be modified only after obtaining fd.
  • The function futimensat can modify the time attribute of a file by creating an absolute path of the file. In this case, the fd parameter is ignored.
  • At the same time, when the target file is a symbolic link, the default function behavior is to track the link to the real file. The parameter flag can modify the default behavior. When the flag value is AT_SYMLINK_NOFOLLOW, the modified file is the symbolic link itself.

The utimes function modifies the file time by specifying a file path pathname.

Function declaration:

#include <sys/time.h>

int utimes(const char *pathname, const struct timeval times[2]);

strcut timeval {

    time_t tv_sec;

    long tv_usec;

};

We cannot specify the modification time field st_ctim (changed-status time), but this field is automatically updated when the utimes function is called.

Example:

Example scenario:

  • Use the open O_TRUNC option to make a file empty and its length is 0;
  • In order not to modify the access time and modification time of the file, use the stat function to obtain the time before modification;
  • The length of the truncated file is 0, and then the futimes function is used to reset the file time field to the time before modification.

Code:

# Include "apue. h"

# Include <fcntl. h>

 

Int

Main (int argc, char * argv [])

{

Int I, fd;

Struct stat statbuf;

Struct timespec times [2];

 

For (I = 1; I <argc; I ++ ){

If (stat (argv [I], & statbuf) <0) {/* fetch current times */

Err_ret ("% s: stat error", argv [I]);

Continue;

}

If (fd = open (argv [I], O_RDWR | O_TRUNC) <0) {/* truncate */

Err_ret ("% s: open error", argv [I]);

Continue;

}

Times [0] = statbuf. st_atim;

Times [1] = statbuf. st_mtim;

If (futimens (fd, times) <0)/* reset times */

Err_ret ("% s: futimens error", argv [I]);

Continue;

}

Times [0] = statbuf. st_atim;

Times [1] = statbuf. st_mtim;

If (futimens (fd, times) <0)/* reset times */

Err_ret ("% s: futimens error", argv [I]);

Close (fd );

}

Exit (0 );

}

Running result: (because the mac OS I use does not support, this example is not compiled successfully, so I directly use the result in the book)

The result shows that the last-modification time and last-access time are not changed, but the changed-status time is changed.

 

3 mkdir, mkdirat, and rmdir Functions

The mkdir and mkdirat functions create a new empty directory. The rmdir function is used to delete the directory.

Function declaration:

#include <sys/stat.h>

int mkdir(const char* pathname, mode_t mode);

int mkdirat(int fd, const char* pathname, mode_t mode);

The value of the mode parameter is based on the file creation mask (file creation mask of process) mentioned in the previous article ).

The rmdir function is used to delete an empty directory that contains only two records (dot and dot-dot ).

Function declaration:

#include <sys/stat.h>

int rmdir(const char* pathname);

The above three functions return 0 if the call is successful, and-1 if the call fails.

 

4. Read the directory file (reading directories)

Anyone with corresponding permissions can read the contents of a directory file. However, to ensure that the system works normally, only the kernel can perform write operations on directory files.

In the previous chapter, we learned that the write permission bit and execution permission limit of directory files determine whether we can create and delete files in this directory, however, they do not allow us to write the directory file itself.

The file read operation depends on the system implementation. The related function declaration is as follows:

#include <dirent.h>

DIR *opendir(const char* pathname);

DIR *fdopendir(int fd);   // return : pointer if OK, NULL on error

struct dirent *readdir(DIR *dp);    // return : pointer if OK, at end of directory or error

void rewinddir(DIR *dp);

int closed(DIR *dp);    // return : 0 if OK, -1 on error

long telluride(DIR *dp);    // return : current location in directory associated with dp

void seekdir(DIR *dp, long loc);

Details:

  • Struct dirent is defined in the header file <dirent. h>, depending on the specific implementation, but contains at least two members: ino_t d_ino (inode number) and char d_name [] (null-terminated filename ).
  • The structure DIR will be discussed in detail in later chapters.
  • Opendir and fdopendir return a pointer to the DIR struct, which will be used in the other five functions.
  • Readdir returns the first record of the directory. When readdir uses the pointer returned by fdopendir, the read record depends on the offset of the fd parameter passed to fdopendir.

 

5 chdir, fchdir, and getcwd Functions

Each process has a working directory, which is an attribute of the process.

Function declaration:

#include <unistd.h>

int chdir(const char* pathname);

int fchdir(int fd);

It is relatively simple and will not be repeated.

If we want to obtain the complete information (absolute path) of the current working directory, we cannot directly obtain it from the kernel, because the kernel only maintains a pointer to this directory.

If we want to obtain the absolute path, we need to go to the parent directory through dot-dot, read the information of the parent directory, get the directory name, and then access the parent directory to the root directory in sequence, finally, extract the absolute path.

The getcwd function implements this function.

Function declaration:

#include <unistd.h>

char* getcwd(char *buf, size_t size);

Note that the buf must be large enough and the size is the size of the buf. The buf must contain an absolute path plus a null terminator in bytes.

Example:

Function: modify the current working directory (chdir) and obtain the absolute path of the working directory (getcwd)

Code:

# Include "apue. h"

 

Int

Main (void)

{

Char * ptr;

Size_t size;

 

If (chdir ("/usr/") <0)

Err_sys ("chdir failed ");

 

Ptr = path_alloc (& size);/* our own function */

If (getcwd (ptr, size) = NULL)

Err_sys ("getcwd failed ");

 

Printf ("cwd = % s \ n", ptr );

Exit (0 );

}

Switch the working directory to/usr/and print the working directory.

 

6. Summary of File Permission bits

See the following table.

7. Summary

This chapter consists of three parts, which focus on the stat function and understand:

  • Each member in the stat struct;
  • Attributes of UNIX files and directories;
  • Common functions for operating files and directories;
  • The organizational structure of UNIX file systems.

In the next chapter, we will learn the standard IO library.

 

References:

Advanced Programming in the UNIX Envinronment 3rd

 

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.