ASCII printing

This commit is contained in:
xamidev
2024-06-02 11:00:06 +02:00
parent b5a70ff093
commit bb97e9825d
3 changed files with 45 additions and 3 deletions

48
hex.c
View File

@@ -1,21 +1,59 @@
#include <stdio.h>
#include <ctype.h>
// TODO: ASCII/Position printing
// TODO: Stop appending garbage at file end
// TODO: Simplify/clean some code (useless condition/loop guard brackets)
#define BYTES 1024
#define BYTES_PER_LINE 10
#define BYTES_PER_LINE 20
void print_hex(unsigned char* buf, int byteno)
{
{
for (int i=0; i<byteno; i++)
{
if (i % BYTES_PER_LINE == 0)
{
if (i != 0)
{
printf(" ");
for (int j=i-BYTES_PER_LINE; j<i; j++)
{
if (isprint(buf[j]))
{
printf("%c", buf[j]);
}
else {
printf(".");
}
}
}
puts("");
}
printf("%.2X ", buf[i]);
}
// ASCII: last line
int padding = BYTES_PER_LINE - (byteno % BYTES_PER_LINE);
if (padding < BYTES_PER_LINE)
{
for (int i=0; i<padding; i++)
{
printf(" ");
}
printf(" ");
}
int start = byteno - (byteno % BYTES_PER_LINE);
for (int j = start; j < byteno; j++) {
if (isprint(buf[j])) {
printf("%c", buf[j]);
}
else {
printf(".");
}
}
puts("");
}
@@ -35,7 +73,7 @@ int main(int argc, char** argv)
for (;;)
{
char cmd;
int loc;
int loc = 0;
scanf("%c%d", &cmd, &loc);
switch(cmd)
{
@@ -51,6 +89,10 @@ int main(int argc, char** argv)
case 'S':
fclose(f);
f = fopen(argv[1], "w");
if (!f) {
perror("Error opening file for writing");
return -1;
}
fwrite(buf, 1, BYTES, f);
fclose(f);
break;