c - 如何从 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"
感觉就像我在尝试重新发明一个轮子。这个问题有什么简单的解决方案吗?一个函数?
解决方案
我刚刚设法为此创建了自己的解决方案。
请注意,此代码片段将在“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
欢迎任何有关代码优化的提示!
推荐阅读
- leaflet - 如何在 Leaflet 中实现 Open Route 服务
- python - 用模式填充缺失值 NAN 在 Pandas 中不起作用
- javascript - 使用javascript减去css左值
- javascript - 概念:如何获取用户在表单中输入的查询/输入,并将它们附加或传递到快速路由内的外部 API 调用?
- python - pygame的登录系统
- sql - 使用递归 CTE 查找直到某个日期的最大值
- python - 如何创建具有动态表面积的可点击小部件?
- javascript - 我正在尝试使用带有 express 的 Sequelize 发布请求来更新我的 SQL 数据库
- python - 使用 Python 设置 Realm 对象属性
- python - 将字符串编码为八进制 utf-8 Python 3