gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 21:05:54 24 4
gpt4 key购买 nike

如何在 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"

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

最佳答案

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

请注意,此代码片段在“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

欢迎任何有关代码优化的建议!

关于c - 如何在 C 中将完整路径(字符串)中的文本附加到文件名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52124986/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com