Bug fixes, error checking; V1 complete
This commit is contained in:
33
hex.c
33
hex.c
@@ -1,7 +1,6 @@
|
||||
#include <stdio.h>
|
||||
#include <ctype.h>
|
||||
|
||||
// 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;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user