如何比较c中的字符

ble*_*ter 0 c linux c-strings cstring standard-library

我有一个小项目,我需要比较一个流的第一个字节.问题是该字节可以是0xe5或任何其他不可打印的字符,因此表示该特定数据是坏的(一次读取32位).我可以允许的有效字符是AZ,az,0-9,'.' 和空间.

目前的代码是:

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.
}
Run Code Online (Sandbox Code Playgroud)

所以问题在于,当我尝试执行以下操作时:

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; 
}
Run Code Online (Sandbox Code Playgroud)

它不起作用.我看到一个字符,如表示黑色六面钻石的字符,里面有问号......理论上它应该只允许以下字符:Space (32), 0-9 (48-57), A-Z (65-90), a-z (97-122)但我不知道为什么它不能正常工作.

我甚至尝试使用ctype.h中的函数 - > iscntrl,isalnum,ispunct但这也没有用.

有人能够用我所假设的一个简单的问题来帮助一个新手吗?这将不胜感激!

谢谢.马丁

ray*_*ylu 7

我不确定你为什么把它投射到int.请考虑使用以下其中一项:

if ((entry[0] >= 'A' && entry[0] <= 'Z') ||
    (entry[0] >= 'a' && entry[0] <= 'z') ||
    entry[0] == ' ' || entry[0] == '.')
Run Code Online (Sandbox Code Playgroud)

要么

#include <ctype.h>
if (isalnum(entry[0]) || entry[0] == ' ' || entry[0] == '.')
Run Code Online (Sandbox Code Playgroud)