Skip to content

Commit 566920e

Browse files
authored
Merge pull request merces#1 from UserXGnu/stdin_support
Adding /dev/stdin reading support
2 parents edf7878 + 55b3ec9 commit 566920e

File tree

2 files changed

+31
-15
lines changed

2 files changed

+31
-15
lines changed

Makefile

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
all:
2-
gcc -Wall -Wextra -pedantic -ansi -o hdump hdump.c
2+
gcc -Wall -Wextra -pedantic -o hdump hdump.c
33

44
install:
55
install -m 0755 hdump /usr/local/bin/hdump

hdump.c

+30-14
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,9 @@
1919

2020
#ifdef __unix__
2121
#define _FILE_OFFSET_BITS 64
22+
23+
#include <unistd.h>
24+
2225
#endif /*__unix__ */
2326

2427
#include <stdio.h>
@@ -90,20 +93,36 @@ int main(int argc, char *argv[])
9093
if (!cols)
9194
cols = 16;
9295

93-
buff = (unsigned char *) calloc (1, sizeof(unsigned char) * cols);
94-
ascii = (unsigned char *) calloc (1, (sizeof(unsigned char) * cols) + 1);
96+
if (!(file = fopen(argv[argc-1], "rb")))
97+
fatal("file not found or not readable");
9598

99+
#ifdef __unix__
96100

97-
if (!buff || !ascii)
98-
fatal("not enough memory");
101+
/*
102+
* Caso o arquivo de entrada seja na verdade uma
103+
* pseudo-tty como /dev/stdin.
104+
*/
105+
if (isatty (fileno (file))) {
106+
for ( ;skip > 0; skip --) {
107+
if (fgetc (file) == EOF)
108+
fatal ("skipping too much");
109+
}
110+
}
99111

100-
if (!(file = fopen(argv[argc-1], "rb")))
101-
fatal("file not found or not readable");
112+
#else
102113

103114
/* anda #skip posicoes para frente (-s) */
104115
if (fseek(file, skip, SEEK_SET))
105116
fatal("unable to seek through file");
106117

118+
#endif /* __unix__ */
119+
120+
buff = (unsigned char *) calloc (1, sizeof(unsigned char) * cols);
121+
ascii = (unsigned char *) calloc (1, (sizeof(unsigned char) * cols) + 1);
122+
123+
if (!buff || !ascii)
124+
fatal("not enough memory");
125+
107126
do
108127
{
109128
bread = (int) fread(buff, sizeof(char), cols, file);
@@ -119,15 +138,12 @@ int main(int argc, char *argv[])
119138
/* imprime os bytes separados por espaço */
120139
printf("%02x%*c", (unsigned int) *(buff+i), (i+1 == cols/2) ? 2 : 1, ' ');
121140

122-
/*
123-
* define o final do array asciii (será usado como string)
124-
* imprime os caracteres ascii
125-
* */
126-
if (i == bread-1)
127-
{
128-
*(ascii+bread) = '\0';
141+
/* define o fim do array ascii (sera usado como string) */
142+
*(ascii+bread) = '\0';
143+
144+
/* imprime os caracteres ascii */
145+
if (i == bread-1)
129146
printf("%*c|%s|\n", get_spaces(bread, cols), ' ', ascii);
130-
}
131147
}
132148
/* atualiza o numero de endereços lidos */
133149
address += bread;

0 commit comments

Comments
 (0)