99 ways to program a hex, Part 11: C89, const correctness, assertive, GCC extensions

Today's code is identical to part 9 [1] save for one line—it uses a GCC extention [2] to notify the compiler that the do_dump() function accepts NULL pointers, and that it won't throw any exceptions.

/*************************************************************************
*************************************************************************/
/* Style: C89, const correctness, assertive, GCC extensions */
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#define LINESIZE 16
static void do_dump (FILE *const,FILE *const) attribute((nonnull,nothrow));
/****************************************************************/
int main(const int argc,char *const argv[])
{
assert(argc >= 1);
assert(argv != NULL);
assert(argv[0] != NULL);
if (argc == 1)
do_dump(stdin,stdout);
else
{
int i;
for (i = 1 ; i < argc ; i++)
{
FILE *fp;
fp = fopen(argv[i],"rb");
if (fp == NULL)
{
perror(argv[i]);
continue;
}
printf("-----%s-----\n",argv[i]);
do_dump(fp,stdout);
fclose(fp);
}
}
return EXIT_SUCCESS;
}
/******************************************************************/
static void do_dump(FILE *const fpin,FILE *const fpout)
{
unsigned char buffer[BUFSIZ];
unsigned char *pbyte;
size_t offset;
size_t bread;
size_t j;
char ascii[LINESIZE + 1];
assert(fpin != NULL);
assert(fpout != NULL);
offset = 0;
while((bread = fread(buffer,1,BUFSIZ,fpin)) > 0)
{
pbyte = buffer;
while (bread > 0)
{
fprintf(fpout,"%08lX: ",(unsigned long)offset);
j = 0;
do
{
fprintf(fpout,"%02X ",*pbyte);
if (isprint(*pbyte))
ascii [j] = *pbyte;
else
ascii [j] = '.';
pbyte ++;
offset ++;
j ++;
bread --;
} while ((j < LINESIZE) && (bread > 0));
ascii [j] = '\0';
if (j < LINESIZE)
{
size_t i;
for (i = j ; i < LINESIZE ; i++) fprintf(fpout," ");
}
fprintf(fpout,"%s\n",ascii);
}
if (fflush(fpout) == EOF)
{
perror("output");
exit(EXIT_FAILURE);
}
}
}
/***************************************************************/

=> [1] /boston/2012/01/17.1 | [2] http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html | [3] /boston/2012/01/18.1 | [4] /boston/2012/01/20.2

=> Gemini Mention this post | Contact the author

Proxy Information
Original URL
gemini://gemini.conman.org/boston/2012/01/19.2
Status Code
Success (20)
Meta
text/gemini
Capsule Response Time
566.919004 milliseconds
Gemini-to-HTML Time
3.505994 milliseconds

This content has been proxied by September (3851b).