4 文件属性和目录操作
一、目录操作
-- 目录操作主要的目的:让程序知道路径下有什么文件存在
-- 注:程序在哪里运行他的工作路径就在哪里 ,程序中所有的相对路径的文件就是基于工作路径来实现的
1、获取当前程序运行的工作路径
-- 函数头文件
- #include <unistd.h>
-- 函数原型
- char *getcwd(char *buf, size_t size);
-- 函数的作用:
- 获取程序运行所在的工作路径
-- 函数的参数:
- buf:用来存放获取到的工作路径的字符串的地址
- size:前面一个指针指向数组的大小
-- 函数的返回值:
- 成功返回 一个字符串的首地址 这个字符串为程序的工作路径
- 失败返回 NULL
#include <unistd.h>
#include <stdio.h>
char *getcwd(char *buf, size_t size);
int main()
{
//第一种:通过返回值
char *p = getcwd(NULL,0);
printf("%s\n",p);
if(p == NULL)
{
perror("getcwd");
}
/*
//第二种,通过参数
char buf[1024];
getcwd(buf,1024);
printf("%s\n",buf);
*/
}
注:上面这个代码中有两种方法获取路径
2、更改程序的工作路径
-- 函数头文件
- #include <unistd.h>
-- 函数原型
- int chdir(const char *path);
-- 函数的作用:
- 更改程序的工作路径
-- 函数的参数:
- path:要进行跳转的工作路径
-- 函数返回值:
- 成功 0
- 失败 -1
#include <unistd.h>
#include <stdio.h>
int main(int argc, char const *argv[])
{
int d = chdir(argv[1]);
if(d == -1)
{
perror("chdir");
}
char *p = getcwd(NULL,0);
printf("%s\n",p);
return 0;
}