这里的问题演示:http://goo.gl/71U1xA
我正在读取一个文件,在那个文件中有一行:
SECTIE FIELD_IN #define ENDSEC
这表明我需要将这一行之后的行存储到一个变量中,但只有该行包含部分“#define
”。
因此,我遍历文件,当该行包含“SECTIE
”和“FIELD_IN
”时,它会检索带有 #
的单词在其中并将其存储在变量 keyWord
中.
现在的问题是:keyWord
中的值在下一个循环中更改而不修改它。
我的文本文件是:
SECTIE FIELD_IN1 #define ENDSEC
#define COL1 1,1
#define COL2 2,3
#define COL3 5,3
...etc
我的代码的输出是这样的:
START reading line text=SECTIE FIELD_IN1 #define ENDSEC keyword1=.. new sectie keyword2=.#define. reading line text=#define COL1 1,1 keyword1=. 1,1 . start = 1! keyword3=. 1,1 .
我的代码:
int x, status, start;
char inputLine[5000 + 1];
char copyLine[5000 + 1];
char *keyWord = "";
FILE *iFile;
status = NOERROR;
x = 0;
start = 0;
iFile = fopen(gsz_inputFile, "r");
if(iFile == NULL){
status = ER_OPEN;
return status;
}
while (fgets(inputLine, sizeof(inputLine), iFile) != NULL){
printf("\n\nreading line");
printf("\ntext=%s", inputLine);
printf("\nkeyword1=.%s.", keyWord);
strcpy(copyLine, inputLine);
strlwr(copyLine);
if(strstr(copyLine, "sectie") != NULL && strstr(copyLine, "field_in") != NULL){
start = 1;
printf("\nnew sectie");
//get keyword
keyWord = strtok(inputLine," ");
while (keyWord != NULL)
{
if(strstr(keyWord, "#") != NULL){
break;
}
keyWord = strtok(NULL, " ");
}
printf("\nkeyword2=.%s.", keyWord); //here the keyword is correct
continue;
}
if(start){
printf("\nstart = 1!");
printf("\nkeyword3=.%s.", keyWord);
//status = storeString(inputLine, keyw, x); //my actual code is different
if(status != NOERROR){ x--; }
x++;
}
}
我认为这与while (fgets(inputLine, sizeof(inputLine), iFile) != NULL)
有关因为在该行执行后,值发生了变化。
为什么keyWord
的值是进入下一个循环后改变?我猜这与未定义的行为有关,但我不能指出这个问题。
最佳答案
您有 inputLine
,它是一个数组。在其中存储由 fgets()
获取的字符串:
while (fgets(inputLine, sizeof(inputLine), iFile) != NULL){
在你的循环中你说 keyWord
指向一些 inputLine 的标记(这意味着它指向你的数组中的某个地方)。
//get keyword
keyWord = strtok(inputLine," ");
当您运行第二个 fgets()
时,数组内容发生了变化,但其地址没有变化,因此 keyWord 仍然指向 inputLine 内容的 已发生变化
例子:
first fgets():
inputLine: ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
keyWord-->""
second strtok:
keyWord------------------------------------^
second fgets():
inputLine: ['T', 'h', 'i', 's', ' ', 'c', 'h', 'a', 'n', 'g', 'e']
keyword------------------------------------^ (before strtok)
您假设“ keyWord
的值已更改”是错误的:关键字的值仍然相同,您可以使用 printf("value关键词:%p\n", keyWord);
。发生变化的是 keyWord
指向 的值,这是您在 printf 中使用 %s
显示的值。
关于c - 为什么我的变量在 strtok() 和 fgets() 之后改变而不修改它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30934606/