首页 > 解决方案 > 如何从 C 中的完整路径(字符串)将文本附加到文件名?

问题描述

如何从 C 中的完整路径(字符串)将文本附加到文件名?

例如:

"/home/erikas/myfile.txt" would become "/home/erikas/myfile-generated.txt"
"/home/erikas/myfile" would become "/home/erikas/myfile-generated"
"/my.directory/my.super.file.txt" would become "/my.directory/my.super.file-generated.txt"

感觉就像我在尝试重新发明一个轮子。这个问题有什么简单的解决方案吗?一个函数?

标签: c

解决方案


我刚刚设法为此创建了自己的解决方案。

请注意,此代码片段将在“myfile.txt”或“/home/my.user/”等完整路径上失败,但在我的情况下,我使用 GTK 选择文件,所以对我来说没有问题:

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

#ifdef _WIN32
#define SEPARATOR '\\'
#else
#define SEPARATOR '/'
#endif

#define GENERATED_APPEND_TEXT "-generated"

char *generate_output_fpath(char* fpath) {
    int last_separator_index = (int) (strrchr(fpath, SEPARATOR) - fpath);
    int last_dot_index = (int) (strrchr(fpath, '.') - fpath);

    char *new_fpath = malloc(strlen(fpath) + strlen(GENERATED_APPEND_TEXT) + 1); // +1 for \0

    if(new_fpath == NULL){
        return NULL; // malloc failed to allocate memory
    }

    // if dot does not exist or dot is before the last separator - file has no extension:
    if ( !last_dot_index || last_dot_index < last_separator_index) {
        new_fpath[0] = '\0'; //ensure it is empty
        strcat(new_fpath, fpath);
        strcat(new_fpath, GENERATED_APPEND_TEXT);
        return new_fpath;
    }

    int fpath_length = strlen(fpath);
    int append_text_length = strlen(GENERATED_APPEND_TEXT);

    int i = 0;
    int ii = 0;
    for (; i < last_dot_index; i++) {
        new_fpath[i] = fpath[i];
    }
    // We copied everything until dot. Now append:
    for (; ii < append_text_length; ii++) {
        new_fpath[i + ii] = GENERATED_APPEND_TEXT[ii];
    }
    // Now append extension with dot:
    for (; i < fpath_length; i++) {
        new_fpath[i + ii] = fpath[i];
    }
    return new_fpath;
}

结果:

"/home/erikas/myfile.txt" would become "/home/erikas/myfile-generated.txt"
"/home/erikas/myfile" would become "/home/erikas/myfile-generated"

请注意,可以在此处查看/测试完整示例:onlinegdb.com/HyPyfTvw7

欢迎任何有关代码优化的提示!


推荐阅读