如何在不使用完整路徑的情況下檢查 APPDATA 中是否存在檔案?
#include <stdio.h>
#include <unistd.h>
#include <windows.h>
int main(void)
{
if (access("%APPDATA%\\changzhi_leidianmac.data", F_OK) != -1)
{
printf("File Found......");
}
else
{
printf("File not found !!!!");
}
return 0;
}
uj5u.com熱心網友回復:
你可以使用getenv
#include <stdlib.h>
int main(void)
{
char *appdata = getenv("APPDATA");
...
...
}
稍后使用snprintf.
uj5u.com熱心網友回復:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main(void)
{
// Define the trailing portion of the file path.
static const char FileName[] = "\\changzhi_leidianmac.data";
// Get the value of environment variable APPDATA or fail if it is not set.
const char *APPDATA = getenv("APPDATA");
if (!APPDATA)
{
fputs("Error, the environment variable APPDATA is not defined.\n",
stderr);
exit(EXIT_FAILURE);
}
printf("APPDATA is %s.\n", APPDATA);
// Figure the space needed. (Note that FileName includes a null terminator.)
size_t Size = strlen(APPDATA) sizeof FileName;
// Get space for the full path.
char *Path = malloc(Size);
if (!Path)
{
fprintf(stderr,
"Error, unable to allocate %zu bytes of memory for file path.\n",
Size);
exit(EXIT_FAILURE);
}
// Copy APPDATA to the space for the path, then append FileName.
strcpy(Path, APPDATA);
strcat(Path, FileName);
printf("Full file path is %s.\n", Path);
// Test whether the file exists and report.
if (0 == access(Path, F_OK))
puts("The file exists.");
else
{
puts("The file does not exist.");
perror("access");
}
}
uj5u.com熱心網友回復:
C 沒有任何訪問 env 變數的規定。您需要使用庫或系統命令來獲取資料。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/360994.html
上一篇:如何在c 中獲得相同的行
