C语言 Windows 下切换到上一级目录
在 Windows 下,可以使用 C 语言的 'chdir()' 函数和 'getcwd()' 函数来实现打开上一级目录。
首先,可以使用 'getcwd()' 函数获取当前工作目录的路径:
#include <stdio.h>
#include <direct.h>
int main() {
char currentPath[256];
if (_getcwd(currentPath, sizeof(currentPath)) != NULL) {
printf("Current working directory: %s\n", currentPath);
} else {
perror("getcwd() error");
return 1;
}
return 0;
}
然后,可以使用 'chdir()' 函数将当前工作目录切换到上一级目录:
#include <stdio.h>
#include <direct.h>
int main() {
char currentPath[256];
if (_getcwd(currentPath, sizeof(currentPath)) != NULL) {
printf("Current working directory: %s\n", currentPath);
if (_chdir("..“) == 0) {
printf("Successfully changed to parent directory.\n");
} else {
perror("chdir() error");
return 1;
}
} else {
perror("getcwd() error");
return 1;
}
return 0;
}
注意,'chdir()' 函数会改变当前工作目录,所以在切换完成后,可以再次使用 'getcwd()' 函数来获取当前工作目录的路径,以确认切换是否成功。
原文地址: https://www.cveoy.top/t/topic/qDgA 著作权归作者所有。请勿转载和采集!