APUE Learning Example Source Code
guowenxue
2023-11-06 d81310d55b9b7d07904c19f879f50e52fd7be489
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <dirent.h>
#include <errno.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
 
 
#define TEST_DIR "testdir"
 
int main(int argc, char **argv)
{
    int               rv;
    int               fd1;
    int               fd2;
    DIR              *dirp;
    struct dirent    *direntp;
 
    if( mkdir(TEST_DIR, 0755)<0 )
    {
        printf("create directory '%s' failure: %s\n", TEST_DIR, strerror(errno));
        return -1;
    }
 
    if( chdir(TEST_DIR)<0 )
    {
        printf("Change directory to '%s' failure: %s\n", TEST_DIR, strerror(errno));
        rv = -2;
        goto cleanup;
    }
 
    if( (fd1=creat("file1.txt", 0644)) < 0 )
    {
        printf("Create file1.txt failure: %s\n", strerror(errno));
        rv = -3;
        goto cleanup;
    }
 
    if( (fd2=creat("file2.txt", 0644)) < 0 )
    {
        printf("Create file2.txt failure: %s\n", strerror(errno));
        rv = -4;
        goto cleanup;
    }
 
    if( chdir("../")<0 )
    {
        printf("Change directory to '%s' failure: %s\n", TEST_DIR, strerror(errno));
        rv = -5;
        goto cleanup;
    }
 
    if((dirp=opendir(TEST_DIR)) == NULL)
    {
        rv = -6;
        printf("opendir %s error: %s\n", TEST_DIR, strerror(errno));
        goto cleanup;
    }
 
    while((direntp = readdir(dirp)) != NULL)
    {
        printf("Find file: %s\n", direntp->d_name);
    }
 
    closedir(dirp);
 
cleanup:
    if(fd1 >= 0)
    {
        close(fd1);
    }
 
    if(fd2 >= 0)
    {
        close(fd2);
    }
 
}