如何在 C 中提取文件路径的最后部分?
How to extract the final part of the file path in C?
我希望能够找到最终路径的最后一部分,并以此为基础制作一个新文件。例如
/Users/use/Projects/projectname/test.txt
基于此,我希望能够创建一个名为
的新文件
test.newfile.txt
我该怎么做?
沿分隔符(此处为“/”)拼接,然后抓取最后一个元素。然后创建一个字符串以用作基于该字符串的新文件名。转述自下面的 link;
#include <stdio.h>
#include <string.h>
int main()
{
char str[] = "strtok splits once per call, call many times to split full string";
int init_size = strlen(str);
char delim[] = "/";
char *ptr = strtok(str, delim);
while(ptr != NULL)
{
last = ptr //[p]oin[t]e[r]
ptr = strtok(NULL, delim);
}
strcat("newfile.", last)
//open a file with that name, write to it, etc.
return 0;
}
来源:https://www.codingame.com/playgrounds/14213/how-to-play-with-strings-in-c/string-split
这将使 "last" 指向最后一次出现的定界符之后的字符串的最后部分,因此只是文件名。然后,您可以使用 strcat() 将字符串与它连接起来。
如果您想要 text.newfile.txt 而不是 newfile.text.txt,您可以再次拆分 text.txt 字符串,这次沿着“.”,并且:
temp = strcat(original_filename, newfile)
new_filename = strcat(temp, original_file_extenstion)
我希望能够找到最终路径的最后一部分,并以此为基础制作一个新文件。例如
/Users/use/Projects/projectname/test.txt
基于此,我希望能够创建一个名为
的新文件test.newfile.txt
我该怎么做?
沿分隔符(此处为“/”)拼接,然后抓取最后一个元素。然后创建一个字符串以用作基于该字符串的新文件名。转述自下面的 link;
#include <stdio.h>
#include <string.h>
int main()
{
char str[] = "strtok splits once per call, call many times to split full string";
int init_size = strlen(str);
char delim[] = "/";
char *ptr = strtok(str, delim);
while(ptr != NULL)
{
last = ptr //[p]oin[t]e[r]
ptr = strtok(NULL, delim);
}
strcat("newfile.", last)
//open a file with that name, write to it, etc.
return 0;
}
来源:https://www.codingame.com/playgrounds/14213/how-to-play-with-strings-in-c/string-split
这将使 "last" 指向最后一次出现的定界符之后的字符串的最后部分,因此只是文件名。然后,您可以使用 strcat() 将字符串与它连接起来。
如果您想要 text.newfile.txt 而不是 newfile.text.txt,您可以再次拆分 text.txt 字符串,这次沿着“.”,并且:
temp = strcat(original_filename, newfile)
new_filename = strcat(temp, original_file_extenstion)