Unix programming learning notes (12)-directory operations for file I/O

Source: Internet
Author: User

Lien000034
2014-09-18

1 Introduction

In Unix systems, a directory is a special file type. We can use the open function to open the directory, obtain the file descriptor, and then call the stat function to obtain the Directory attribute information, but we cannot use the READ function to read the directory content. For example, the following example shows,

#include <stdlib.h>#include <stdio.h>#include <errno.h>#include <string.h>#include <fcntl.h>#include <unistd.h>#include <sys/stat.h>#define BUF_LEN 2014intmain(void){    int fd;    char buffer[BUF_LEN];    struct stat statbuf;    if ((fd = open("mydir", O_RDONLY)) < 0) {        printf("open mydir error: %s\n", strerror(errno));        exit(-1);    }    if (fstat(fd, &statbuf) < 0) {        printf("fstat error: %s\n", strerror(errno));        exit(-1);    }    if (S_ISDIR(statbuf.st_mode)) {        printf("mydir is directory\n");    }    if (read(fd, buffer, BUF_LEN) < 0) {        printf("read mydir error: %s\n", strerror(errno));        exit(-1);    }    printf("mydir: %s\n", buffer);    exit(0);}

Compile the program, generate the file readdir, and then run readdir,

Lien000034: Demo $ LS-ldrwxrwxr-x 2 lien000034 lien000034 40969 mydirlien000034: Demo $ gcc-O readdir. clien000034: Demo $. /readdirmydir is directoryread mydir error: is a directory

Based on the running results above, it is not difficult to find that an error is returned when the READ function reads the directory. UNIX provides a set of operation functions for directories.

2. Create a directory

The mkdir function allows you to create directories.

# Include <sys/STAT. h>

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

Returned value: 0 is returned if the request is successful, and-1 is returned if an error occurs.

Mkdir function is a new empty directory. The directory items... And. are automatically created. The mode specified here and the file mode Creation blocking word of the process jointly determine the file access permission of the new directory (refer to "blocking and changing File Access Permissions ".)

Note: In "file access permission and process access control", we learned that the directory execution permission is used for file search, therefore, when the mkdir function is called to specify the mode parameter, at least one execution permission limit is set.

3. delete a directory

The rmdir function can delete an empty directory. An empty directory is a directory that contains only the ".." and.

# Include <unistd. h>

Int rmdir (const char * pathname );

Returned value: 0 is returned if the request is successful, and-1 is returned if an error occurs.

Calling the rmdir function will reduce the link count of the directory by 1. If the link count of the directory is reduced to 0 and no other process opens the directory, the space occupied by the Directory will be released. If a process opens this directory when the link count reaches 0, a later link and a... item will be deleted before the function returns. In addition, you cannot create new files in this directory.

Example 1:

The following example shows how to delete a non-empty directory named mydir.

#include <stdlib.h>#include <stdio.h>#include <errno.h>#include <string.h>#include <unistd.h>intmain(void){    if (rmdir("mydir") < 0) {        printf("rmdir mydir error: %s\n", strerror(errno));    } else {        printf("succ rmdir mydir");    }    exit(0);}

Compile the program, generate rmdirdemo, and then run the file,

Lien000034: Demo $ LS-L total mydir usage 8-rw-rw-r -- 1 lien000034 lien000034 September 18 20:21 file1-rw-rw-r -- 1 lien000034 lien000034 9 September 18 20:22 file2lien000034: Demo $ gcc-O rmdirdemo. clien000034: Demo $. /rmdirdemormdir mydir error: directory not empty

Example 2:

The following program deletes the empty directory emptydir and creates a new file in the directory before the process exits,

#include <stdlib.h>#include <stdio.h>#include <errno.h>#include <string.h>#include <fcntl.h>#include <unistd.h>#include <sys/stat.h>intmain(void){    int fd;    if ((fd = open("emptydir", O_RDONLY)) < 0) {        printf("open emptydir error: %s\n", strerror(errno));        exit(-1);    }    if (rmdir("emptydir") < 0) {        printf("rmdir emptydir error: %s\n", strerror(errno));        exit(-1);    }    printf("rmdir emptydir succ\n");    if (creat("emptydir/foo", S_IRUSR | S_IWUSR) < 0) {        printf("creat error: %s\n", strerror(errno));        exit(-1);    }    printf("creat succ\n");    exit(0);}

Compile the program, generate the file rmdirdemo, and then run the file,

Lien000034: Demo $ LS-L total emptydir usage 0lien000034: Demo $ gcc-O rmdirdemo. clien000034: Demo $./rmdirdemormdir emptydir succcreat error: no such file or directory
4. Read directory content

Any user who has access to a directory can read the directory. However, the kernel can only write the directory. In addition, the actual format of directories depends on Unix systems, especially the specific design and implementation of their file systems. To isolate applications from these specific implementation details, Unix provides a set of routines related to read directories.

# Include <dirent. h>
Dir * opendir (const char * pathname );
Return Value: If successful, return true. If an error occurs, return null.

Struct dirent * readdir (dir * DP );
Return Value: if the operation succeeds, a pointer is returned. If the operation fails at the end of the Directory, null is returned.

Void rewinddir (dir * DP );

Int close (dir * DP );
Returned value: 0 is returned if the request is successful, and-1 is returned if an error occurs.

Long telldir (dir * DP );
Returned value: the current location in the directory associated with DP.

Void seekdir (dir * DP, long LOC );

The dirent structure defined in the header file <dirent. h> is related to the implementation. However, it contains at least two members:

struct dirent {    ino_t d_ino;     /* i-node number */    char d_name[NAME_MAX + 1];    /* filename */}

The opendir function opens a directory and performs initialization to make the first read directory in the first readir directory.

Example:

The following program compiles all directory items under the directory mydir and prints the names of each directory item.

#include <stdlib.h>#include <stdio.h>#include <errno.h>#include <string.h>#include <dirent.h>intmain(void){    DIR *dp;    struct dirent *dirp;    if ((dp = opendir("mydir")) == NULL) {        printf("opendir mydir error: %s\n", strerror(errno));        exit(-1);    }    while ((dirp = readdir(dp)) != NULL) {        printf("%s\n", dirp->d_name);    }    if (closedir(dp) < 0) {        printf("closedir error: %s\n", strerror(errno));        exit(-1);    }    exit(0);}

Compile the program, generate the file readdir, and then run the file,

lienhua34:demo$ gcc -o readdir readdir.clienhua34:demo$ ./readdir..file2.file1

According to the running results of the above program, the order of reading various directory items in the directory is not listed alphabetically.

5. Switch the working directory of the process

Each process has a current working directory, which is the starting point for searching all relative pathnames. A process can call the chdir or fchdir function to change the current working directory.

# Include <unistd. h>

Int chdir (const char * pathname );

Int fchdir (INT filedes );

Return values of the two functions: 0 if the function is successful, or-1 if the function is successful.

The current working directory is an attribute of the process. Changing the current working directory of the process only affects the process that calls the chdir function, but does not affect other processes.

In addition, Unix also provides the getcwd function to obtain the current working directory of the process.

# Include <unistd. h>

Char * getcwd (char * Buf, size_t size );

Return Value: if the operation succeeds, the Buf is returned. If an error occurs, the return value is null.

The first parameter of the getcwd function is the buffer address Buf, and the second parameter is the buffer length size (unit: bytes ). The buffer must have enough length to hold the absolute path name and add a null termination character.

Example:

The following program first prints the current working directory, then calls chdir to switch the working directory, and finally calls getcwd to obtain and print the new working directory.

#include <stdlib.h>#include <stdio.h>#include <unistd.h>#include <errno.h>#include <string.h>#define BUF_LEN 2014intmain(void){    char buf[BUF_LEN];    if (getcwd(buf, BUF_LEN) < 0) {        printf("getcwd error: %s\n", strerror(errno));        exit(-1);    }    printf("cwd before chdir: %s\n", buf);    if (chdir("/home/lienhua34/program") < 0) {        printf("chdir error: %s\n", strerror(errno));        exit(-1);    }    if (getcwd(buf, BUF_LEN) < 0) {        printf("getcwd error: %s\n", strerror(errno));        exit(-1);    }    printf("cwd before chdir: %s\n", buf);    exit(0);}

Compile the program, generate the file cwddemo, and then run the file,

lienhua34:demo$ gcc -o cwddemo cwddemo.clienhua34:demo$ ./cwddemocwd before chdir: /home/lienhua34/program/c/apue/ch04/democwd before chdir: /home/lienhua34/program

(Done)

Unix programming learning notes (12)-directory operations for file I/O

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.