I’m trying to open a file using an absolute path. I’m currently doing this in Windows but will also need this to work in a Unix environement.
The path is composed using an environment variable as shown below.
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");
This code prints out C:\Data/index/index.tbl but the application fails to open the file.
What am I doing wrong?
This is incorrect:
and may be overwriting a part of the process’ environment block. From man getenv:
You need to allocate a buffer large enough to contain the full path and copy in
getenv("DATA")and thenstrcat()orsprintf():