首先,我們需要的變量讀值到:
int x, y, z /* etc */;
現在,讓我們做一個指針數組,這樣我們就可以很容易地訪問的變量:
int *array[] = { &x, &y, &z /* etc */ };
現在,我們需要一個FILE*
訪問該文件:
FILE* fp;
打開文件:
fp = fopen("filename.txt", "r"); /* 'r' for reading */
檢查如果文件成功打開:
if(fp == NULL)
{
printf("Error opening file");
exit(-1); /* Exit the program */
}
現在,閱讀使用fscanf
文件:
int counter = 0; /* For keeping track of the array index */
for(;;) { /* Infinite loop */
int retVal = fscanf(fp, "%d", array[counter]); /* Capture return value of fscanf */
if(retVal == 1) /* Successfully scanned a number */
{
counter++;
}
else if(retVal == 0) /* Failed to scan a number */
{
fscanf(fp, "%*s"); /* Discard a word from the file */
}
else /* EOF */
{
break; /* Get out of the loop */
}
}
現在,打印掃描的數據:
int i;
for(i = 0; i < counter; i++)
printf("%d", *array[i]);
最後,關閉文件:
fclose(fp);
的完整代碼,添加@ Jongware的建議:
int x, y, z /* etc */;
int *array[] = { &x, &y, &z /* etc */ };
char line[1024];
const char *varNames[] = { "x", "y", "z" };
int tmp = -1;
FILE* fp;
fp = fopen("filename.txt", "r"); /* 'r' for reading */
if(fp == NULL)
{
printf("Error opening file");
exit(-1); /* Exit the program */
}
int counter = 0;
for(fgets(line, sizeof(line), stdin)) {
if(line[0] == '%')
continue;
else
{
tmp = -1;
for(int i = 0; i < sizeof(varNames)/sizeof(*varNames); i++)
{
if(strcmp(line, varNames[i]) == 0)
{
tmp = i;
break;
}
}
fgets(line, sizeof(line), stdin);
sscanf(line, "%d", array[tmp]);
}
}
int i;
for(i = 0; i < counter; i++)
printf("%d", *array[i]);
fclose(fp);
所有上面的代碼是未經測試
我不認爲這是可能的。您不能在運行時確定具有特定名稱的新變量。 –
Python通過將所有變量保留在字典中來實現這一點。 –
變量*名稱*只存在於您的C源代碼中,而不存在於已編譯的可執行文件中。在某些情況下,甚至可以將變量*值*完全優化。 – usr2564301