Skip to content

Instantly share code, notes, and snippets.

@brunoczim
Last active June 2, 2017 15:04
Show Gist options
  • Save brunoczim/3e468afc4334d282662ace6a749eeed6 to your computer and use it in GitHub Desktop.
Save brunoczim/3e468afc4334d282662ace6a749eeed6 to your computer and use it in GitHub Desktop.
A very simple C program for inspecting binaries.
/*
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stdio.h>
#include <string.h>
#include <errno.h>
void inspect(FILE *file, unsigned width);
int main(int argc, const char **argv) {
unsigned width = 1;
char width_arg[] = "-w";
const char *filename = NULL;
{
int i;
for (i = 1; i < argc; i++) {
if (strcmp(argv[i], width_arg) == 0) {
i++;
if (i >= argc) {
fprintf(stderr, "Expecting one more argument after %s.\n", width_arg);
return 1;
}
sscanf(argv[i], "%u\n", &width);
} else {
filename = argv[i];
}
}
}
if (filename == NULL) {
inspect(stdin, width);
} else {
FILE *file = fopen(filename, "r");
if (file == NULL) {
fprintf(stderr, "Error opening %s: %s.\n", filename, strerror(errno));
return 2;
}
inspect(file, width);
fclose(file);
}
return 0;
}
void inspect(FILE *file, unsigned width) {
int ch = fgetc(file);
long long unsigned i = 0;
while (ch != EOF) {
char ch_str[2] = {ch, 0};
char *toprint = NULL;
switch (ch) {
case '\n':
toprint = "\\n";
break;
case '\b':
toprint = "\\b";
break;
case '\r':
toprint = "\\r";
break;
case '\0':
toprint = "\\0";
break;
case '\f':
toprint = "\\f";
break;
case '\v':
toprint = "\\v";
break;
case '\t':
toprint = "\\t";
break;
case 27:
toprint = "\\ESC";
break;
case 127:
toprint = "\\DEL";
break;
default:
toprint = ch_str;
break;
}
printf("[%llu]: %u (%s)", i, ch, toprint);
ch = fgetc(file);
if ((i + 1) % width == 0 || ch == EOF) fputc('\n', stdout);
else fputs(" | ", stdout);
i++;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment