On 2006-04-27,
vi********@gmail.com <vi********@gmail.com> wrote:
Hi ,
writing a small application in C which has to create an XML document by
reading a binary format file. Trying to get the indentation right by
using a depth global variable which will insert appropriate number of
tab spaces depending up on the depth.
Is there any way that this can be done using a macro.
So , something like
#define INSERTTAB (x) /* not sure what will come here */
INSERTTAB (depth)
The only reason I can think of for a macro (rather than a function) is
because you want a macro that expands to a string literal:
printf(INSERTTAB(n)"%s\n", tag);
which needs to expand to:
printf("\t\t\t\t""%s\n", "hello");
I'm fairly sure there's no way to do this-- even if the C preprocessor
had more functionality, n isn't known until runtime, so it's got to be
runtime code that "prints" the tabs one way or another.
You could try:
printf("%s%s\n", make_tabs(n), tag);
where make_tabs returns a string of tabs. But then you have to worry
about allocating strings. There are various options, but none of them
are very nice if the indent level gets high.
So a function to actually put the tabs in is your best bet I would say:
void insert_tabs(FILE *fp, unsigned n)
{
...
}
insert_tabs(stdout, 4);
printf("%s\n", tag);
The other option you've got is perhaps generate the xml without any
indentation at all, and then pipe it through one of the many xml
indentation programs that exist-- the xslt program to do this is
practically a one-liner.