C语言获取当前工作路径

目前做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;
}


  • 10
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值