I have a small project i am doing that requires comparing the first byte of a stream. The problem is that that byte can be 0xe5 or any other non printable character, and thus denoting that that particular data is bad (reading it 32 bits at a time). The valid characters I can allow are A-Z, a-z, 0-9, '.' and space.
The current code is:
FILE* fileDescriptor; //assume this is already open and coming as an input to this function.
char entry[33];
if( fread(entry, sizeof(unsigned char), 32, fileDescriptor) != 32 )
{
return -1; //error occured
}
entry[32] = '\0'; //set the array to be a "true" cstring.
int firstByte = (int)entry[0];
if( firstByte == 0 ){
return -1; //the entire 32 bit chunk is empty.
}
if( (firstByte & 0xe5) == 229 ){ //denotes deleted.
return -1; //denotes deleted.
}
So the problem is that when i tried to do the following:
if( firstByte >= 0 && firstByte <= 31 ){ //NULL to space in decimal ascii
return -1;
}
if( firstByte >= 33 && firstByte <= 45 ){ // ! to - in decimal ascii
return -1;
}
if( firstByte >= 58 && firstByte <= 64 ) { // : to @ in decimal ascii
return -1;
}
if( firstByte >= 91 && firstByte <= 96 ) { // [ to ` in decimal ascii
return -1;
}
if( firstByte >= 123 ){ // { and above in decimal ascii.
return -1;
}
it doesn't work. I see characters such as the one that denotes a black six sided diamond with a question mark inside 开发者_StackOverflowof it... Theoretically it should've only let the following characters: Space (32), 0-9 (48-57), A-Z (65-90), a-z (97-122)
, but i don't know why it is not working properly.
I even tried using the functions in ctype.h -> iscntrl, isalnum, ispunct but that also didn't work.
Would anyone be able to help a fellow c newb with what I am assuming is a simple c problem? It would be greatly appreciated!
Thanks. Martin
I'm not sure why you are casting it to an int. Consider using one of the following:
if ((entry[0] >= 'A' && entry[0] <= 'Z') ||
(entry[0] >= 'a' && entry[0] <= 'z') ||
entry[0] == ' ' || entry[0] == '.')
or
#include <ctype.h>
if (isalnum(entry[0]) || entry[0] == ' ' || entry[0] == '.')
精彩评论