我正在尝试逐行读取配置文件,然后将结果标记化并将结果存储到单独的变量中。我的配置文件如下所示
stage 1
num_nodes 2
nonce 234567
我需要分别标记该行中的每个值,因此例如在第一行“stage”中用于检查我是否已从配置文件中读取阶段值,然后将其值保存在变量中。我的标记化似乎工作正常。但是,当我在标记化后尝试操纵我的变量时,它会给我一个分段错误。至多我只能成功地操纵其中一个变量,即 stage 或 num_nodes 或 nonce 但不是它们的组合。即使尝试做类似的事情
stage = stage + 1;
num_nodes = num_nodes + 1;
但是,如果我只是对一个变量进行更改,这会导致分段错误,例如:
num_nodes = num_nodes + 1;
然后它工作正常。我正在粘贴下面的代码,请告诉我我在这里缺少什么。
main(int argc, char *argv[]){
int nonce;
int num_nodes;
int stage;
char filename[256];
char *token1, *token2, *str;
FILE* fp;
char bufr[MAXLINE];
printf("Please enter config file name\n");
scanf("%s",filename);
printf("You entered %s\n", filename);
if((fp = fopen(filename, "r")) != NULL){
while(fgets(bufr, MAXLINE, fp) != NULL){
if(bufr[0] == '#') // to skip comments
continue;
printf("This is bufr: %s", bufr);
str = bufr;
for(str; ;str = NULL){
token1 = strtok(str, " ");
if(strcmp(token2, "num_nodes") == 0){
num_nodes = atoi(token1);
printf("num_nodes = %d\n", num_nodes);
}
if(strcmp(token2, "nonce") == 0){
nonce = atoi(token1);
printf("nonce = %d\n", nonce);
}
if(strcmp(token2, "stage") == 0){
stage = atoi(token1);
printf("stage = %d\n", stage);
}
token2 = token1; // making a copy of pointer
if(str == NULL){
break;
}
}//end of for loop
}//end of while loop
fclose(fp); //close the file handle
}
else{
printf("failed, file not found!\n");
}
/* This is where the segmentation fault kicks in, try to uncomment two lines and it will give a segmentation fault, if uncomment just one, then it works fine.
nonce = nonce + 2;
num_nodes = num_nodes + 1;
printf("stage = %d\n", stage);
*/
}