C语言将文件目录和文件名拼装为一个完整路径
时间: 2024-05-02 22:19:52 浏览: 15
这是一个编程相关的问题,我可以为您提供解答。在C语言中,可以使用sprintf函数将文件目录和文件名拼装为一个完整路径。具体操作可以参照以下示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
int main()
{
char dir[] = "/root";
char file[] = "test.txt";
char path[100];
sprintf(path, "%s/%s", dir, file);
printf("完整路径为:%s\n", path);
return 0;
}
```
以上代码可以将字符串"/root"和"test.txt"拼接为完整路径"/root/test.txt",并输出该路径。
相关问题
写一个Linux c语言打印指定目录下文件名的函数
可以使用 `opendir()` 和 `readdir()` 函数来实现该功能。下面是一个简单的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
void list_files(const char *path) {
DIR *dir;
struct dirent *entry;
dir = opendir(path);
if (dir == NULL) {
perror("opendir");
exit(EXIT_FAILURE);
}
while ((entry = readdir(dir)) != NULL) {
if (entry->d_type == DT_REG) { // 如果是普通文件
printf("%s\n", entry->d_name);
}
}
closedir(dir);
}
```
在该函数中,首先通过 `opendir()` 函数打开指定目录,如果打开失败,则输出错误信息并退出程序。然后通过 `readdir()` 函数循环读取目录下的文件项,对于每个文件项,如果是一个普通文件,则输出文件名。最后通过 `closedir()` 函数关闭目录。需要注意的是,这里只输出了普通文件的文件名,如果需要输出其他类型的文件名,需要修改 `if` 语句中的条件判断。
c语言输入一个带有路径的完整文件名,剔除路径将文件名输出
```c
#include <stdio.h>
#include <string.h>
int main() {
char filename[100];
printf("请输入带有路径的完整文件名:\n");
scanf("%s", filename);
char *p = strrchr(filename, '/');
if (p != NULL) {
printf("文件名为:%s\n", p + 1);
} else {
printf("文件名为:%s\n", filename);
}
return 0;
}
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)