diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..fb52516 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +minihex diff --git a/README.md b/README.md index 8d62ae0..fcb2f20 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,13 @@ # minihex -A minimalist, single-file hexadecimal editor written in C with no dependencies (except the standard library). The program tries to be as simple as possible. Many bugs exist. +A minimalist, single-file hexadecimal editor written in less than 100 lines of C with no dependencies (except the standard library). The program tries to be as simple as possible. +Other features might be added in the future. + +## Usage + +``` +make +./minihex +``` + +To get help with the commands, do not provide any filename. diff --git a/hex.c b/hex.c index 3a0866f..91f6f16 100644 --- a/hex.c +++ b/hex.c @@ -1,7 +1,6 @@ #include #include -// TODO: Stop appending garbage at file end // TODO: Skip repeating lines #define BYTES 1024 @@ -13,7 +12,6 @@ void print_hex(unsigned char* buf, int byteno, int pos) { if (i % BYTES_PER_LINE == 0) { - //printf("%03d: ", lineno); if (i != 0) { printf(" "); @@ -26,7 +24,7 @@ void print_hex(unsigned char* buf, int byteno, int pos) puts(""); // Here, we could print positions in hex but I prefer using integers. printf("%04X ", i); if (pos == 0) printf("\x1b[1;34m%06d:\x1b[0m ", i); - else printf("\x1b[34m%06d:\x1b[0m ", pos); + else printf("\x1b[1;34m%06d:\x1b[0m ", pos); } printf("%.2X ", buf[i]); } @@ -58,7 +56,12 @@ int main(int argc, char** argv) return -1; } - FILE* f = fopen(argv[1], "r"); + FILE* f = fopen(argv[1], "rb+"); + if (!f) + { + printf("Error opening file %s\n", argv[1]); + return -1; + } unsigned char buf[BYTES]; int byteno = fread(buf, 1, BYTES, f); print_hex(buf, byteno, 0); @@ -69,31 +72,25 @@ int main(int argc, char** argv) int loc; scanf(" %c", &cmd); - if (cmd == 'p' || cmd == 'P' || cmd == 'e' || cmd == 'E') scanf("%d", &loc); + if (cmd == 'p' || cmd == 'e') scanf("%d", &loc); switch(cmd) { - case 'p': - case 'P': + case 'p': print_hex(buf + loc, BYTES_PER_LINE, loc); break; case 'e': - case 'E': - scanf("%hhx", buf + loc); + int value; + scanf("%x", &value); + if (loc < byteno) buf[loc] = (unsigned char)value; break; case 's': - case 'S': - fclose(f); - f = fopen(argv[1], "w"); - if (!f) { - perror("Error opening file for writing"); - return -1; - } - fwrite(buf, 1, BYTES, f); + fseek(f, 0, SEEK_SET); + fwrite(buf, 1, byteno, f); fclose(f); + return 0; break; case 'q': - case 'Q': return 0; } } diff --git a/minihex b/minihex index 6982c7a..9a3f1a0 100755 Binary files a/minihex and b/minihex differ diff --git a/test.txt b/test.txt index 4426f9b..a281799 100644 --- a/test.txt +++ b/test.txt @@ -1,3 +1,3 @@ -?eÿlo, from a text file. +ÿÿÿÿo, from a text file. This is a public service announcement -brought to you in part by Slim Shady lol +brought to you inCpart by Slim Shady lol