줄 단위로 구성 파일을 읽고 tokenize하고 결과를 별도의 변수에 저장하려고합니다. 내 구성 파일과 같은 다음파일을 한 줄씩 읽고 C에서 strtok()를 사용하여
stage 1
num_nodes 2
nonce 234567
내가 확인하는 데 사용되는 첫 번째 줄 "단계"의 예를 들어 내가 구성 파일에서 단계의 값을 읽을 경우, 그래서 별도로 라인에 각 값을 토큰 화하는 데 필요 그 값을 변수에 저장하십시오. 내 토큰 화가 올바로 작동하는 것 같습니다. 그러나 토큰 화 후에 변수를 조작하려고하면 세그먼트 오류가 발생합니다. 대부분 나는 변수 중 하나, 즉 스테이지 또는 num_node 또는 nonce 중 하나만 성공적으로 조작 할 수 있지만 그 조합은 성공적으로 조작 할 수 없습니다.
num_nodes = num_nodes + 1;
다음 잘 작동 :
stage = stage + 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);
*/
}
: 여기
http://www.hyperrealm.com/libconfig/
당신은 예를 볼 수 있습니다 token1, 즉 token2 = token1이며 두 번째 반복에서 마지막 반복에서 읽은 토큰을 확인하고 그에 따라 변수를 업데이트하는 데 사용됩니다. –
'token2'가 설정되어 있지 않을 때 걱정되는 첫 번째 반복문입니다. 나는 코드를 탐험 중이다. 지금 당장은 내가 가지고있는 버전이 많은 문제를 안고 있다고 말할 수있다. 그러나 토큰을 사용하기 전에'token2 = ""'를 설정한다. (초기화되지 않은 변수에 액세스하는 것은 재앙을위한 처방이다.) –
그 점에 동의하십시오. –