我可以删除最后一条if语句吗?

时间:2012-01-02 06:29:37

标签: c

我写了一个小实用程序来打开可执行程序并吐出它找到的某些可打印字符串。

它工作正常,但我想知道,有什么方法可以删除其中一个if语句?我试图看看如何安排我的条件,所以我不需要3个不同的if语句,但我不知道如何用当前的结构来做它。

#include <stdio.h>

#define MAX_STR_SIZE 0x666
#define MIN_STR_SIZE 0x5

int main(int argc, char** argv) 
{
    int ch;
    int pos = 0;
    FILE* f;
    char buff[MAX_STR_SIZE];

    if (argc>1 && (f=fopen(argv[1], "rb")))
    {
        while ((ch=getc(f)) != EOF)
        {
            if (ch >= ' ' && ch <= 'z') // is printable char?
            {
                buff[pos++] = ch;
                buff[pos] = '\0';
                if (pos == (MAX_STR_SIZE-1))  // is current string > max length?
                {
                    printf("%08x: %s\n", ftell(f), &buff[0]);
                    pos = 0;
                }
            }
            else // non-printable char, print any string in buffer and start over
            {
                if (pos > (MIN_STR_SIZE - 1)) // is current string > min string?
                {
                    printf("%08x: %s\n", ftell(f), &buff[0]); // print current string
                }
                pos = 0;
            }
        }

        if (pos > (MIN_STR_SIZE - 1)) // any remaining string left to print?
        {
            printf("%08x: %s\n", ftell(f), &buff[0]);
        }

        fclose(f);
    }
}

2 个答案:

答案 0 :(得分:3)

最后if似乎是代码当前逻辑所必需的。

但是,检查代码并不完全正确。为什么不使用isprint()函数来检查字符是否可打印?像这样:

if (isprint(c)) // is printable char?
{
  //c is printable
}

答案 1 :(得分:3)

我相信这个版本消除了大多数if语句(或至少将它们折叠在一起:

#include <stdio.h>

#define MAX_STR_SIZE 0x666
#define MIN_STR_SIZE 0x5

int main(int argc, char** argv) 
{
    int ch;
    int pos = 0;
    FILE* f;
    char buff[MAX_STR_SIZE];

    if (argc>1 && (f=fopen(argv[1], "rb")))
    {
        while ((ch = getc(f)) != EOF)
        {
            pos = 0;
            while (ch >= ' ' && ch <= 'z' && pos < (MAX_STR_SIZE-1)) {
                buff[pos++] = ch;
                ch = getc(f);
            }
            if (pos > (MIN_STR_SIZE - 1)) // is current string > min string?
            {
                buff[pos] = '\0';
                printf("%08x: %s\n", ftell(f), buff);
            }
        }

        fclose(f);
    }
}
相关问题