I’ve written a small utility to open up executables and spit out certain printable strings it finds.
It works fine but I was wondering, is there some way I could remove one of these if statements? I was trying to see how I could arrange my conditionals so I wouldn’t need the 3 different if statements but I don’t see how I can do it with the current structure.
#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);
}
}
I believe this version eliminates most of the if statements (or at least collapses them together: