我有一个小程序可以在文件中搜索一些字符串。 这个字符串的末尾有一个可变部分,并且前面总是有一个字节来表示大小。
例如,我们将在“aaaaa.http://www.example.combbbbb”中查找“http://”(“.”的 ASCII 码为 0x17。
假设我们已经打开了文件。 要执行的代码是:
while(car != EOF){
car = fgetc(file[ii]); // we get everything in the file
lastBuffStart=ftell(file[ii]);
ij=1;
buffer[0]=car; // we start editing the buffer
printf("\n%d (%c) - %d (%c) ",car,car,base[0],base[0]);
while(ij<(buffsize-1)){
buffer[ij]=fgetc(file[ii]);
printf("\n | %d (%c) - %d (%c) ",buffer[ij],buffer[ij],base[ij],base[ij]);
ij++;
}
fseek(file[ii],lastBuffStart,0); // we get back to the old position before the buffer continues
if(strcmp(buffer,base)==0){ // we compare
byteSize = (ftell(file[ii])-1); // we get the position of the size byte
printf("\nFound : 0x%x\n",byteSize);
}
}
我们读取所有文件并将下一个字符放入缓冲区以与基址(http://)进行比较。
我的问题是如果我们删除 printf("\n | %d (%c) - %d (%c) ",buffer[ij],buffer[ij],base[ij],base[ij] ); 没有找到...
我真的看不出我做错了什么。
你能帮帮我吗?
提前致谢。
最佳答案
您忘记了以 null 终止缓冲区。或者,您应该使用 memcmp 而不是 strcmp。此外,如果您使用 fread 而不是 while 循环,代码会更清晰。
关于c - strcmp 行为怪异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6482754/