You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从strrchr()或strchr()提取剩余子串?以文件路径为例

Extract Directory Path from File Path Using strrchr()

Great question! Since you're already leveraging strrchr() for filename extraction, we can extend that exact same lightweight approach to grab the directory path—no messy strtok(), regex, or tedious loops required. Here's how to do it efficiently, with attention to common edge cases:

Step 1: Locate the Last Slash

First, reuse strrchr() to find the final / in your path string—this is the dividing line between the directory and filename:

char *filepath = "this/is/my/path/to/file.jpg";
char *last_slash = strrchr(filepath, '/');

Always check if last_slash is not NULL first! This handles cases where the path has no slashes (e.g., just file.jpg), so you can decide how to handle those scenarios (return the original string, empty string, etc.).

Option 1: Modify the Original String (If Allowed)

If your filepath is a mutable buffer (e.g., a stack-allocated array or heap-allocated string, not a string literal which is read-only), this is the most efficient method—no extra memory allocation needed:

if (last_slash != NULL) {
    *last_slash = '\0'; // Replace the '/' with a null terminator
    // Now `filepath` holds "this/is/my/path/to"
    char *filename = last_slash + 1; // Still works for the filename!
}

This works because C strings are null-terminated—truncating the string at the last slash immediately turns filepath into the directory path. Just be sure you don't need the original full path anymore, or make a copy first if you do.

Option 2: Preserve the Original String (Read-Only Paths)

If your filepath is a read-only string literal (like in your example), you'll need to allocate a new buffer to store the directory path. We calculate the exact length needed to avoid wasted space:

char *dir_path = NULL;
if (last_slash != NULL) {
    size_t path_length = last_slash - filepath; // Number of chars in the directory path
    dir_path = malloc(path_length + 1); // +1 for the null terminator
    if (dir_path != NULL) {
        strncpy(dir_path, filepath, path_length);
        dir_path[path_length] = '\0'; // Explicitly add the null terminator (strncpy doesn't always do this)
        // Use dir_path as needed...
        free(dir_path); // Don't forget to free when done!
    }
}

This approach is still extremely efficient: we only traverse the string once with strrchr(), then copy exactly the characters we need—no unnecessary operations.

Edge Case Handling

  • If last_slash is NULL (no slashes in the path), you can choose to set dir_path to an empty string, or the original filepath, depending on your use case.
  • For Windows paths using \, just replace '/' with '\\' (escape the backslash in C strings).

内容的提问来源于stack exchange,提问作者blackbeard

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:32:35