使用C语言完成文件名切割
时间: 2024-10-15 11:23:37 浏览: 24
在C语言中,你可以使用标准库中的`strtok`函数或者手动编写循环来分割文件路径。不过需要注意的是,`strtok`会修改原字符串,因此如果你需要保留原始字符串,最好复制一份。下面是一个使用`strtok`的例子,假设你已经有了一个包含完整路径的字符串`pathname`:
```c
#include <stdio.h>
#include <string.h>
char* strtok_copy(char *s, const char *delim, char **saveptr) {
*saveptr = strtok(s, delim);
if (*saveptr) {
size_t len = strlen(*saveptr) + 1;
char *copy = malloc(len);
strncpy(copy, *saveptr, len);
copy[len - 1] = '\0'; // 添加终止符
return copy;
} else {
return NULL;
}
}
int main() {
char pathname[] = "/path/to/myfile.txt";
char *token;
token = strtok_copy(pathname, "/", &pathname); // 分割第一个部分
while (token != NULL) {
printf("Token: %s\n", token);
token = strtok(NULL, "/"); // 继续分割,直到结束
}
free(pathname); // 不要忘记释放内存
return 0;
}
```
这个程序会打印出每个目录层级,直到文件名。注意,当`strtok`返回NULL时,意味着已经到达了路径的结尾。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20210720083447.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)