简体   繁体   English

在C中的可执行目录中设置文件名

[英]Setting up the name of a file in the executable directory in C

I have to create a buffer to hold the the name of a license file which is in the executable directory.我必须创建一个缓冲区来保存可执行目录中的许可证文件的名称。 This is my solution (I'm not a C programmer):这是我的解决方案(我不是 C 程序员):

char buffer[MAX_PATH] = "";
GetModuleFileName(NULL, buffer, MAX_PATH);
int len = (int) strlen(buffer);
buffer[len-7] = '\0';
strcat(buffer,"license.lic");

Note I know the name of the executable is net.exe - 7 chars, so I'm cheating.注意我知道可执行文件的名称是 net.exe - 7 chars,所以我在作弊。

Firstly is this code safe?首先,这段代码安全吗? I got a compiler warning about using strcat saying I should use strcat_s, but I couldn't get that working.我收到一个关于使用 strcat 的编译器警告说我应该使用 strcat_s,但我无法让它工作。

Secondly how do I get the correct length of the executable name?其次,我如何获得可执行名称的正确长度?

Your code is reasonably safe.您的代码相当安全。 Assuming MAX_PATH is the maximum possible length of a pathname, replacing the executable name with license.lic should fit in that size.假设MAX_PATH是路径名的最大可能长度,用license.lic替换可执行文件名应该适合该大小。

Rather than getting the length of the executable name, you can search for the last directory delimiter character, and copy license.lic after it.您可以搜索最后一个目录分隔符,然后在其后复制license.lic ,而不是获取可执行文件名称的长度。 C has a built-in function strrchr() for searching a string in reverse. C 有一个内置的 function strrchr strrchr()用于反向搜索字符串。

char *sepptr = strrchr(buffer, '\\');
if (sepptr == NULL) {
    sepptr = buffer; // no directory delimiter, replace it completely
} else {
    sepptr++; // point to just past the delimiter
}
strcpy(sepptr, "license.lic"); // Overwrite executable name with license name

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM