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

如何在C语言中提取文件名后缀并与指定字符串拼接?

How to Append File Extension to "output" Filename in C

Got it, let's walk through exactly how to solve this. You're already ahead using strrchr to grab the last occurrence of '.' (that's the right way to get the file extension). Now we just need to safely glue that extension to your outputfilename string.

Key Considerations First

Before diving into code, remember:

  • Always check if strrchr returns NULL—that means the original file has no extension, so we should just use "output" as-is (or treat it as an empty extension).
  • Never assume your output buffer is big enough—buffer overflow is a common bug here, so either use dynamic memory allocation (safer for unknown lengths) or a sufficiently sized fixed buffer with checks.

This is the best approach if you don't know how long the extension might be, since it allocates exactly the memory you need.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main() {
    char *outputfilename = "output";
    char *original_filename = "report.pdf"; // Replace with your actual input filename
    char *ext = strrchr(original_filename, '.');

    // Handle case where there's no file extension
    if (ext == NULL) {
        ext = ""; // Fallback to empty string so we just get "output"
    }

    // Calculate total length needed: output name + extension + null terminator
    size_t total_length = strlen(outputfilename) + strlen(ext) + 1;
    char *final_filename = (char *)malloc(total_length);

    // Check if malloc succeeded (critical to avoid crashes)
    if (final_filename == NULL) {
        perror("Failed to allocate memory");
        return 1;
    }

    // Copy base name and append extension
    strcpy(final_filename, outputfilename);
    strcat(final_filename, ext);

    // Use your final filename here
    printf("Final filename: %s\n", final_filename);

    // Don't forget to free the allocated memory!
    free(final_filename);
    return 0;
}

Method 2: Fixed Buffer (For Small, Known Sizes)

If you're working in a constrained environment or know the maximum possible length of the final filename, a fixed buffer works. Just make sure to add safety checks to avoid overflow.

#include <stdio.h>
#include <string.h>

// Define a buffer size large enough for your use case
#define MAX_FILENAME_LENGTH 256

int main() {
    char *outputfilename = "output";
    char *original_filename = "profile.jpg";
    char *ext = strrchr(original_filename, '.');
    if (ext == NULL) {
        ext = "";
    }

    char final_filename[MAX_FILENAME_LENGTH];

    // Use snprintf for safer string building (prevents overflow automatically)
    int result_len = snprintf(final_filename, MAX_FILENAME_LENGTH, "%s%s", outputfilename, ext);
    
    // Check if truncation happened (optional but useful for debugging)
    if (result_len >= MAX_FILENAME_LENGTH) {
        fprintf(stderr, "Warning: Final filename was truncated due to buffer size\n");
    }

    printf("Final filename: %s\n", final_filename);
    return 0;
}

Pro Tips

  • snprintf is more robust than strcpy + strcat in fixed buffer scenarios—it won't write past the buffer limit, and its return value tells you if the string was truncated.
  • For dynamic allocation, always pair malloc with free to avoid memory leaks, especially if your code runs repeatedly (like in a loop).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:15:16