473,607 Members | 2,659 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

fprintf format specifiers

Good Day,

Is there a way to print 8 bytes in a line in a file using
fprintf...like this

12 76 89 76 86 34 98 08
A4............. ............... ..

Oct 12 '06 #1
9 3880
Harry said:
Good Day,

Is there a way to print 8 bytes in a line in a file using
fprintf...like this

12 76 89 76 86 34 98 08
A4............. ............... ..
Nope. But of course you can do something like this:

int ch;
int i = 0;
while((ch = getc(fpin)) != EOF)
{
fprintf(fpout, " %02X", ch);
if(++i % 8 == 0)
{
i = 0;
putc('\n', fpout);
}
}
if(i 0)
{
putc('\n', fpout);
}
--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Oct 12 '06 #2
Richard Heathfield wrote:
Harry said:
>Good Day,

Is there a way to print 8 bytes in a line in a file using
fprintf...li ke this

12 76 89 76 86 34 98 08
A4............ ............... ...

Nope. But of course you can do something like this:
Well - one could read 8 bytes, and do
fprintf(fpout, "%02X %02X %02X %02X %02X %02X %02X %02X\n",
buf[0],buf[1],buf[2],buf[3],buf[4],buf[5],buf[6],buf[7]);

Assuming he wanted a hexadecimal representation of each
of the individual byte values.
int ch;
int i = 0;
while((ch = getc(fpin)) != EOF)
{
fprintf(fpout, " %02X", ch);
if(++i % 8 == 0)
{
i = 0;
putc('\n', fpout);
}
}
if(i 0)
{
putc('\n', fpout);
}
Oct 12 '06 #3
"Nils O. Selåsdal" said:
Richard Heathfield wrote:
>Harry said:
>>Good Day,

Is there a way to print 8 bytes in a line in a file using
fprintf...lik e this

12 76 89 76 86 34 98 08
A4........... ............... ....

Nope. But of course you can do something like this:
Well - one could read 8 bytes, and do
fprintf(fpout, "%02X %02X %02X %02X %02X %02X %02X %02X\n",
buf[0],buf[1],buf[2],buf[3],buf[4],buf[5],buf[6],buf[7]);
....er, oh yeah, so he can. :-)

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Oct 12 '06 #4
Richard Heathfield wrote:
Harry said:
Is there a way to print 8 bytes in a line in a file using
fprintf...like this

12 76 89 76 86 34 98 08
A4............. ............... ..

Nope. But of course you can do something like this:

int ch;
int i = 0;
while((ch = getc(fpin)) != EOF)
{
fprintf(fpout, " %02X", ch);
if(++i % 8 == 0)
{
i = 0;
putc('\n', fpout);
}
}
if(i 0)
{
putc('\n', fpout);
}
How about:

char b[8];
...
fprintf(fpout, "%02x", b[0]);
for (i = 1, i < 8; i++) fprintf(fpout, " %02x", b[i]);
putc(fpout, '\n');

or

fprintf(fpout, "%02x %02x %02x %02x %02x %02x %02x %02x\j",
b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7]);

--
Some informative links:
<news:news.anno unce.newusers
<http://www.geocities.c om/nnqweb/>
<http://www.catb.org/~esr/faqs/smart-questions.html>
<http://www.caliburn.nl/topposting.html >
<http://www.netmeister. org/news/learn2quote.htm l>
<http://cfaj.freeshell. org/google/>
Oct 12 '06 #5
Richard Heathfield <in*****@invali d.invalidwrote:
Well - one could read 8 bytes, and do
fprintf(fpout, "%02X %02X %02X %02X %02X %02X %02X %02X\n",
buf[0],buf[1],buf[2],buf[3],buf[4],buf[5],buf[6],buf[7]);
...er, oh yeah, so he can. :-)
Yes, but what about the (likelier) case where the file has a number of
bytes that isn't a multiple of 8? Your original version handled that
easily; the suggested version less so. I'm presuming, possibly
incorrectly, that fprintf() is expensive relative to sprintf(), so
perhaps something like this would be good (criticisms welcome):

#include <stdio.h>
#include <assert.h>

#define BYTES_PER_LINE 8

int main( int argc, char *argv[] )
{
char outbuf[3*BYTES_PER_LIN E+1], *bufptr;
int inchar, count=0;
FILE *fpin, *fpout;

assert( argc 2 );
assert( (fpin = fopen(argv[1],"r")) != NULL );
assert( (fpout = fopen(argv[2],"w")) != NULL );
bufptr = outbuf;
while( (inchar=fgetc(f pin)) != EOF ) {
bufptr += sprintf( bufptr, "%02X ", inchar ); /* assume success */
if( ++count % BYTES_PER_LINE == 0 ) {
*(bufptr-1)='\n';
fputs( outbuf, fpout );
bufptr = outbuf;
}
}
if( bufptr != outbuf ) {
*(bufptr-1)='\n';
fputs( outbuf, fpout );
}
assert( !fclose(fpin) );
assert( !fclose(fpout) );
return 0;
}

--
C. Benson Manica | I *should* know what I'm talking about - if I
cbmanica(at)gma il.com | don't, I need to know. Flames welcome.
Oct 12 '06 #6
Christopher Benson-Manica said:
Richard Heathfield <in*****@invali d.invalidwrote:
Well - one could read 8 bytes, and do
fprintf(fpout, "%02X %02X %02X %02X %02X %02X %02X %02X\n",
buf[0],buf[1],buf[2],buf[3],buf[4],buf[5],buf[6],buf[7]);
>...er, oh yeah, so he can. :-)

Yes, but what about the (likelier) case where the file has a number of
bytes that isn't a multiple of 8? Your original version handled that
easily;
Naturellement.. .
the suggested version less so.
....mais, m'sieur, le question originale ne called pas for une solution
generale. Il merely required pour huit bytes to be ecri a stdout, oui?
I'm presuming, possibly
incorrectly, that fprintf() is expensive relative to sprintf(), so
perhaps something like this would be good (criticisms welcome):

#include <stdio.h>
#include <assert.h>

#define BYTES_PER_LINE 8

int main( int argc, char *argv[] )
{
char outbuf[3*BYTES_PER_LIN E+1], *bufptr;
I'd be tempted to make the "bytes per line" value configurable at runtime.
int inchar, count=0;
FILE *fpin, *fpout;

assert( argc 2 );
assert( (fpin = fopen(argv[1],"r")) != NULL );
assert( (fpout = fopen(argv[2],"w")) != NULL );
Three consecutive poor uses of assert. (I suspect you know this. I'm merely
heads-upping for newbies' benefit.)
bufptr = outbuf;
while( (inchar=fgetc(f pin)) != EOF ) {
bufptr += sprintf( bufptr, "%02X ", inchar ); /* assume success */
if( ++count % BYTES_PER_LINE == 0 ) {
*(bufptr-1)='\n';
Does that overwrite the null terminator? I haven't checked, and perhaps it
doesn't, but the safety of the code is not obvious at a (cursory) glance.
fputs( outbuf, fpout );
bufptr = outbuf;
}
}
if( bufptr != outbuf ) {
*(bufptr-1)='\n';
fputs( outbuf, fpout );
}
assert( !fclose(fpin) );
assert( !fclose(fpout) );
Two more poor uses of assert. If you must do this, spin them around. If you
can't close the input file, it would be good to at least have had a stab at
closing the output file before the abort.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Oct 12 '06 #7

"Christophe r Benson-Manica" <at***@otaku.fr eeshell.orgwrot e in message
news:eg******** **@chessie.cirr .com...
Richard Heathfield <in*****@invali d.invalidwrote:
Well - one could read 8 bytes, and do
fprintf(fpout, "%02X %02X %02X %02X %02X %02X %02X %02X\n",
buf[0],buf[1],buf[2],buf[3],buf[4],buf[5],buf[6],buf[7]);
...er, oh yeah, so he can. :-)

Yes, but what about the (likelier) case where the file has a number of
bytes that isn't a multiple of 8? Your original version handled that
easily; the suggested version less so. I'm presuming, possibly
incorrectly, that fprintf() is expensive relative to sprintf(), so
perhaps something like this would be good (criticisms welcome):
In that case, you'd use fread() with the size of a fixed buffer. fread()
will return the quantity read. This will either be the size of the buffer,
or a smaller quantity. So, you need two printing loops: one for the entire
buffer, and one for the remaining bytes. Both of which have been shown.
Rod Pemberton
Oct 13 '06 #8
On Fri, 13 Oct 2006, Rod Pemberton wrote:
>
"Christophe r Benson-Manica" <at***@otaku.fr eeshell.orgwrot e in message
news:eg******** **@chessie.cirr .com...
>Richard Heathfield <in*****@invali d.invalidwrote:
>>>Well - one could read 8 bytes, and do
fprintf(fpou t, "%02X %02X %02X %02X %02X %02X %02X %02X\n",
buf[0],buf[1],buf[2],buf[3],buf[4],buf[5],buf[6],buf[7]);
>>...er, oh yeah, so he can. :-)

Yes, but what about the (likelier) case where the file has a number of
bytes that isn't a multiple of 8? Your original version handled that
easily; the suggested version less so. I'm presuming, possibly
incorrectly, that fprintf() is expensive relative to sprintf(), so
perhaps something like this would be good (criticisms welcome):

In that case, you'd use fread() with the size of a fixed buffer. fread()
will return the quantity read. This will either be the size of the buffer,
or a smaller quantity. So, you need two printing loops: one for the entire
buffer, and one for the remaining bytes. Both of which have been shown.
In theory one could also use Duff's device:

int n = (count + 7) / 8;

switch (count % 8) {
case 0: do { printf("%02X ", *from++);
case 7: printf("%02X ", *from++);
case 6: printf("%02X ", *from++);
case 5: printf("%02X ", *from++);
case 4: printf("%02X ", *from++);
case 3: printf("%02X ", *from++);
case 2: printf("%02X ", *from++);
case 1: printf("%02X ", *from++);
putchar('\n');
} while (--n 0);
}

Tak-Shing
Oct 13 '06 #9
Richard Heathfield <in*****@invali d.invalidwrote:
...mais, m'sieur, le question originale ne called pas for une solution
generale. Il merely required pour huit bytes to be ecri a stdout, oui?
Ah, le Francais, le langue d'amour! It sounds like you remember as
much of it as I do ;-) (Tu as raison.)
I'd be tempted to make the "bytes per line" value configurable at runtime.
A rare time to give oneself over to the seductive whisperings of
temptation with nary a pang of guilt...
Three consecutive poor uses of assert. (I suspect you know this. I'm merely
heads-upping for newbies' benefit.)
Right, they were quick cover-my-bases hacks.
while( (inchar=fgetc(f pin)) != EOF ) {
bufptr += sprintf( bufptr, "%02X ", inchar ); /* assume success */
if( ++count % BYTES_PER_LINE == 0 ) {
*(bufptr-1)='\n';
Does that overwrite the null terminator? I haven't checked, and perhaps it
doesn't, but the safety of the code is not obvious at a (cursory) glance.
No, bufptr points to the null terminator, assuming per the comment
that sprintf() doesn't do anything unexpected; the code overwrites
the last space in the string. The fact that it wasn't obvious to
you probably means it isn't the best plan, but it does work.
Two more poor uses of assert. If you must do this, spin them around. If you
can't close the input file, it would be good to at least have had a stab at
closing the output file before the abort.
Agreed, thank you.

--
C. Benson Manica | I *should* know what I'm talking about - if I
cbmanica(at)gma il.com | don't, I need to know. Flames welcome.
Oct 13 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
2290
by: Josiah Carlson | last post by:
Good day everyone, I have produced a patch against the latest CVS to add support for two new formatting characters in the struct module. It is currently an RFE, which I include a link to at the end of this post. Please read the email before you respond to it. Generally, the struct module is for packing and unpacking of binary data. It includes support to pack and unpack the c types: byte, char, short, long, long long, char, *, and...
11
5930
by: Grumble | last post by:
Hello, I have the following structure: struct foo { char *format; /* format string to be used with printf() */ int nparm; /* number of %d specifiers in the format string */ /* 0 <= nparm <= 4 */ };
6
3488
by: hpy_awad | last post by:
I am writing stings ((*cust).name),((*cust).address)to a file using fgets but rabish is being wrote to that file ? Look to my source please and help me finding the reason why this rabish is being written. /* Book name : File name : E:\programs\cpp\iti01\ch10\ex09_5p1.cpp Program discription: Adding name,Address to customer_record SETUP PROGRAM
3
3156
by: Andrew Fabbro | last post by:
I have code with stuff like this all over it: sprintf(errmsg,"somefunc(): %s has illegal character %c",somestring,somechar); fatal_error(errmsg); where fatal_error() just fprintf's to stderr and exits. I'd like to change the above to something like: fatal_error("somefunc(): %s has illegal character
6
2992
by: Magix | last post by:
Hi, I want to use fprintf to write to a file. My question about the formatted output How can I format so that I can allocate certain width for each %s (Left-aignlied) ? Example: fprintf("%s %s %s %s, name, age, city, status); <-------------------><----------------><----------------><------------->
1
4212
by: Chris Morse | last post by:
Hi, I've been trying to figure out where in the documentation it describes all the String.Format() formatting specifiers. So far, I've been guessing and picking up specifiers in sample code.. but I've never seen a detailed descriptions of all that's possible. For example, Dim n As Integer = 65536
5
4104
by: Gary Wessle | last post by:
Hi I am trying to pretty print to file 3 vectors (int,double,double) where all the cells match like a table format where every thing lines up to the left and space padded to the right. does c++ has something or mostly use C fprintf? 1255251 0.251025 215.2541 thats how I like it to look, where the space is to the right of the number and the number left aligns with the field border.
3
12789
by: stathisgotsis | last post by:
Hello everyone, Trusting K&R2 i thought until recently that spaces are ignored in scanf's format string. Reading arguments to the contrary confused me a little. So i now ask: Is scanf("%d%d",...) different from scanf("%d %d",...) in the Standard's point of view? Thank you.
11
4284
by: David Mathog | last post by:
In the beginning (Kernighan & Ritchie 1978) there was fprintf, and unix write, but no fwrite. That is, no portable C method for writing binary data, only system calls which were OS specific. At C89 fwrite/fread were added to the C standard to allow portable binary IO to files. I wonder though why the choice was made to extend the unix function write() into a standard C function rather than to extend the existing standard C function...
0
8050
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
7987
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8464
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8130
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
6805
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6000
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4015
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2464
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1574
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.