c - 如何比较c中的字符

标签 c linux cstring standard-library c-strings

我正在做一个小项目,需要比较流的第一个字节。问题在于该字节可以是 0xe5 或任何其他不可打印的字符,因此表示该特定数据是错误的(一次读取 32 位)。我可以允许的有效字符是 A-Z、a-z、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.
}

所以问题是当我尝试执行以下操作时:

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; 
}

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

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

谁能帮助一个 c 新手解决我假设是一个简单的 c 问题?将不胜感激!

谢谢。 马丁

最佳答案

我不确定您为什么要将其转换为 int。考虑使用以下之一:

if ((entry[0] >= 'A' && entry[0] <= 'Z') ||
    (entry[0] >= 'a' && entry[0] <= 'z') ||
    entry[0] == ' ' || entry[0] == '.')

#include <ctype.h>
if (isalnum(entry[0]) || entry[0] == ' ' || entry[0] == '.')

关于c - 如何比较c中的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5785519/

相关文章:

c - 在 C 中实现 Split 函数

c++ - OpenCV:如何在图像上应用彩虹渐变图?

iphone - 如何从服务器(而非 Web 服务器)最好地为 >10,000 个 iPhone 客户端提供服务

c - 循环遍历所有可能的长度为 n 的字符串

c++ - sprintf 如何与 CString 和 std::string 一起工作

Clang 循环优化会导致段错误?

c# - 如何从 sourcecode.c 创建 DLL 库,然后在 C# 中使用它

php - 我如何在我的 php 应用程序中显示 web 根目录之外的图像?

python - 在接口(interface)启动时,可以扫描特定的 MAC 地址吗?

c - C 中的字符串数组