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
54
55
56
57
58
59
60
61
62
63
/*********************************************************************************
 *      Copyright:  (C) 2025 LingYun IoT System Studio
 *                  All rights reserved.
 *
 *       Filename:  mymv.c
 *    Description:  This file is rename() example.
 *                 
 *        Version:  1.0.0(10/15/2025)
 *         Author:  Guo Wenxue <guowenxue@gmail.com>
 *      ChangeLog:  1, Release initial version on "10/15/2025 03:27:05 PM"
 *                 
 ********************************************************************************/
 
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <errno.h>
#include <string.h>
 
/**
 * Checks if a path points to a regular file
 * @param path The file path to check
 * @return 1 if regular file, 0 otherwise
 */
int is_regular_file(const char *path)
{
    struct stat path_stat;
    if (lstat(path, &path_stat) == -1)
    {
        return 0;
    }
    return S_ISREG(path_stat.st_mode);
}
 
int main(int argc, char *argv[])
{
    // Check command line arguments
    if (argc != 3)
    {
        fprintf(stderr, "Usage: %s <source_path> <destination_path>\n", argv[0]);
        return EXIT_FAILURE;
    }
 
    const char *oldpath = argv[1];
    const char *newpath = argv[2];
 
    // Verify source is a regular file
    if (!is_regular_file(oldpath))
    {
        fprintf(stderr, "Error: '%s' is not a regular file\n", oldpath);
        return EXIT_FAILURE;
    }
 
    // Attempt the rename operation
    if (rename(oldpath, newpath) == -1)
    {
        fprintf(stderr, "Error: %s\n", strerror(errno));
        return EXIT_FAILURE;
    }
 
    printf("Successfully renamed '%s' to '%s'\n", oldpath, newpath);
    return EXIT_SUCCESS;
}