Reputation: 67960
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);
}
}
Upvotes: 1
Views: 127
Reputation: 8116
I believe this version eliminates most of the if statements (or at least collapses them together:
#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);
}
}
Upvotes: 3
Reputation: 361332
The last if
seems to be necessary for the current logic of the code.
However, the check in your code is not entirely correct. Why don't you use isprint()
function to check whether a character is printable or not? Something like this:
if (isprint(c)) // is printable char?
{
//c is printable
}
Upvotes: 3