用c 怎么获取当前程序所在的路径

用c 怎么获取当前程序所在的路径,第1张

要用 c++ 程序

#include <windows.h>

#include <string>

#include <iostream>

using namespace std

string ExePath() {

char buffer[MAX_PATH]

GetModuleFileName( NULL, buffer, MAX_PATH )

string::size_type pos = string( buffer ).find_last_of( "\\/" )

return string( buffer ).substr( 0, pos)

}

int main() {

cout <<"my directory is " <<ExePath() <<"\n"

}

=====

c 程序,也许可以通过char *argv[] 寻找,

int main(int argc, char *argv[]){。。。。}

argv[0] 含程序名,可以尝试 用 system() 调 DOS 命令查找:

#include<stdio.h>

int main(int argc, char *argv[])

{

FILE *fp

char s[80]

sprintf(s,"DIR %s.c >a.log",argv[0])

system(s) // 执行后,屏幕输出 存入 a.log 文本文件

fp =fopen("a.log","r") // 打开文件

// 这里 一行一行地读文件,找到 关键词 Directory of , 例如:

// Directory of D:\ZZ\C\example

// D:\ZZ\C\example 就是当前路径

return 0

}

C#获取当前路径的方法如下:

1、System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName

-获取模块的完整路径。

2、System.Environment.CurrentDirectory

-获取和设置当前目录(该进程从中启动的目录)的完全限定目录。

3、System.IO.Directory.GetCurrentDirectory()

-获取应用程序的当前工作目录。这个不一定是程序从中启动的目录啊,有可能程序放在C:\www里,这个函数有可能返回C:\Documents and Settings\ZYB\,或者C:\Program Files\Adobe\,有时不一定返回什么。

4、 System.AppDomain.CurrentDomain.BaseDirectory

-获取程序的基目录。

5、System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase

-获取和设置包括该应用程序的目录的名称。

6、System.Windows.Forms.Application.StartupPath

-获取启动了应用程序的可执行文件的路径。效果和2、5一样。只是5返回的字符串后面多了一个"\"而已。

7、System.Windows.Forms.Application.ExecutablePath

-获取启动了应用程序的可执行文件的路径及文件名,效果和1一样。


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/yw/11169293.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-14
下一篇 2023-05-14

发表评论

登录后才能评论

评论列表(0条)

保存