作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
如何在 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/
我是一名优秀的程序员,十分优秀!