APUE course source code
guowenxue
2 days ago 9c22371ef5059a2e46226ee90a0667ffad65b574
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
/*********************************************************************************
 *      Copyright:  (C) 2025 LingYun IoT System Studio
 *                  All rights reserved.
 *
 *       Filename:  myrm.c
 *    Description:  This file is unlink() example.
 *                 
 *        Version:  1.0.0(10/15/2025)
 *         Author:  Guo Wenxue <guowenxue@gmail.com>
 *      ChangeLog:  1, Release initial version on "10/15/2025 03:01:48 PM"
 *                 
 ********************************************************************************/
 
#include <stdio.h>
#include <unistd.h>
#include <sys/stat.h>
#include <errno.h>
#include <string.h>
 
int main(int argc, char *argv[])
{
    struct stat file_stat;
    const char *file_path;
    
    if (argc != 2)
    {
        fprintf(stderr, "Usage: %s <file_path>\n", argv[0]);
        return 1;
    }
 
    file_path = argv[1];
 
    if (lstat(file_path, &file_stat) == -1)
    {
        fprintf(stderr, "Cannot access file '%s': %s\n", file_path, strerror(errno));
        return 1;
    }
 
    if (!S_ISREG(file_stat.st_mode))
    {
        fprintf(stderr, "'%s' is not a regular file\n", file_path);
        return 1;
    }
 
    if (unlink(file_path) == -1)
    {
        fprintf(stderr, "Delete file '%s' falied: %s\n", file_path, strerror(errno));
        return 1;
    }
 
    printf("File '%s' deleted successfully\n", file_path);
    return 0;
}