使用绝对路径打开文件
问题描述:
我想使用绝对路径打开文件。我目前正在Windows中执行此操作,但也需要在Unix环境中工作。使用绝对路径打开文件
该路径使用环境变量组成,如下所示。
char *dataPath = getenv ("DATA");
strcat(dataPath, "/index");
char indexPath[255] = {0};
strcat(indexPath, dataPath);
strcat(indexPath, "/index.tbl");
printf("Path: %s\n", indexPath);
ip = fopen(indexPath, "r");
此代码打印出C:\ Data/index/index.tbl,但应用程序无法打开文件。
我在做什么错?
答
这是不正确的:
char *dataPath = getenv ("DATA");
strcat(dataPath, "/index");
,并且可以重写过程环境块的一部分。从man getenv:
通常情况下,getenv()返回一个指向环境列表中的字符串的指针。调用者必须注意不要修改该字符串,因为这会改变进程的环境。
您需要分配足够大,以包含完整路径的缓冲区和getenv("DATA")
复制,然后strcat()
或sprintf()
:
const char* dataPath = getenv("DATA");
char* fullPath = 0;
if (dataPath)
{
/* 6 for "/index" and 1 for terminating null character. */
fullPath = malloc(strlen(dataPath) + 6 + 1);
if (fullPath)
{
sprintf(fullPath, "%s/index", dataPath);
free(fullPath);
}
}