目前做C语言程序都在windows下进行,目前就windows下获取当前目录的方法进行一个总结。
第一种方法:_getcwd()
char* _getcwd( char *buffer, int maxlen );
// 功 能 : 获得当前工作目录.
// 头文件 : #include <direct.h>
// 返回值 : 成功返回指向buffer的pointer
// 失败返回NULL,且设置errno为以下三个值之一:
// ENODEV 无该设备
// ENOMEM 内存不够
// ERANGE 结果超出范围
// 注 意 : 当第一个参数为 NULL 时, 第二个参数 maxlen 长度设置无效,且函数
// 使用 malloc 分配足够内存, 需要将函数返回值传递给 free() 函数来
// 释放内存. 当第一个参数不为 NULL 时,maxlen 指定长度不够函数返回
// 错,设置errno为ERANGE
实例:
#include <stdio.h>
#include <direct.h>
#define MAXPATH 1024
int main()
{
char buffer[MAXPATH];
_getcwd(buffer,MAXPATH);
printf("%s",buffer);
return 0;
}
第二种方法:GetCurrentDirectory
Call this member function to get the name of the current directory
BOOL GetCurrentDirectory(
LPTSTR pstrDirName,
LPDWORD lpdwLen
) const;
实例:
#include <stdio.h>
#include <Shlwapi.h>
#include <iostream>
#pragma comment(lib,"Shlwapi.lib")
int main()
{
TCHAR buffer[MAX_PATH];
GetCurrentDirectory(MAX_PATH,buffer);
//D:\Documents\Visual Studio 2010\Projects\MyCode\Lab1
OutputDebugString(buffer);
return 0;
}
第三种方法:GetModuleFileName()
此函数的说明参考https://msdn.microsoft.com/en-us/library/windows/desktop/ms683197(v=vs.85).aspx
实例:
#include <iostream>
#include <Windows.h>
#include <Shlwapi.h>
#pragma comment(lib,"Shlwapi.lib")
using namespace std;
int main(int argc, char * argv[])
{
TCHAR buffer[MAX_PATH];
ZeroMemory(buffer,MAX_PATH);
if (GetModuleFileName(NULL,buffer,MAX_PATH))
{
OutputDebugString(buffer);
//path:D:\Documents\Visual Studio 2010\Projects\MyCode\Lab1\Debug\Lab1.exe
PathRemoveFileSpec(buffer);
//D:\Documents\Visual Studio 2010\Projects\MyCode\Lab1\Debug
}
return 0;
}
第四种方法:main()函数参数
main(int argc,char * argv[]),argv[0]代表当前运行程序的路径
实例:
#include <stdio.h>
#include <Shlwapi.h>
#include <iostream>
#pragma comment(lib,"Shlwapi.lib")
int main(int argc, char * argv[])
{
char *buffer;
puts(argv[0]);
//D:\Documents\Visual Studio 2010\Projects\MyCode\Lab1\Debug\lab1.exe
buffer=argv[0];
PathRemoveFileSpec(buffer);
puts(buffer);
return 0;
}