获取当前工作目录及上级目录,C代码实现
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <direct.h>
#include <memory.h>
#include <string.h>
/*
*@bref 获取当前工作目录
*/
void get_current_directory(char* root)
{
char rootPath[256] = { 0 };
char *buffer = NULL;
if ((buffer = _getcwd(NULL, 0)) == NULL)
{
printf_s(" _getcwd function get current working directory failed! \n");
}
else
{
sprintf_s(rootPath, 256,"%s", buffer);
free(buffer);
}
for (int i = 0; i < sizeof(rootPath); i++)
{
if (rootPath[i] == '\\')
{
rootPath[i] = '/';
}
}
memcpy(root, rootPath, sizeof(rootPath));
}
/*
*@bref 获取当前工作目录的上级目录
*/
void get_parent_directory(char* root)
{
char parPath[256] = { 0 };
get_current_directory(parPath);
int index = 0;
char * result = strrchr(parPath, '/'); // search from back to front
if (result != NULL) {
index = result - parPath;
}
char rootPath[256] = { 0 };
strncpy_s(rootPath, 256, parPath, index);
memcpy(root, rootPath, sizeof(rootPath));
}
测试用例:
int main()
{
static char root[256] = { 0 };
get_current_directory(root);
printf("current directory : %s \n", root);
printf("\n");
memset(root, 0, 256);
get_parent_directory(root);
printf("parent directory : %s\n", root);
getchar();
return 0;
}
输出结果: