[xml] xmlSaveToFd: unexpected behavior while redirecting the 'stdout' stream to a file
- From: YuGiOhJCJ Mailing-List <yugiohjcj-mailinglist laposte net>
- To: xml gnome org
- Subject: [xml] xmlSaveToFd: unexpected behavior while redirecting the 'stdout' stream to a file
- Date: Tue, 3 Apr 2018 14:02:46 +0200
Hello,
I think I found an unexpected behavior of the 'xmlSaveToFd' function while redirecting the 'stdout' stream to
a file, with libxml2 2.9.4.
Here is the code:
---
#include <libxml/xmlsave.h> /* for xmlSaveToFd */
#include <stdio.h> /* for printf */
#include <string.h> /* for strlen */
int main()
{
const char *str = "<html
xmlns=\"http://www.w3.org/1999/xhtml\">\n<head>\n<title>test</title>\n</head>\n<body>\n<p>test</p>\n</body>\n</html>\n";
xmlSaveCtxtPtr ctxt = NULL;
xmlDocPtr doc = NULL;
printf("Content-Type: application/xhtml+xml;\n\n");
/* The line below is really important.
* If it is omitted, then the command './main.out 1>1.txt' will redirect lines from the 'stdout'
stream to the '1.txt' file in the wrong order.
*/
/* fflush(stdout); */
doc = xmlParseMemory(str, strlen(str) + 1);
ctxt = xmlSaveToFd(1, NULL, XML_SAVE_FORMAT);
if(ctxt == NULL)
{
fprintf(stderr, "Unable to create the document saving context.\n");
exit(EXIT_FAILURE);
}
if(xmlSaveDoc(ctxt, doc) == -1)
{
fprintf(stderr, "Unable to save the document to the document saving context.\n");
exit(EXIT_FAILURE);
}
if(xmlSaveClose(ctxt) == -1)
{
fprintf(stderr, "Unable to close the document.\n");
exit(EXIT_FAILURE);
}
xmlFreeDoc(doc);
xmlCleanupParser();
exit(EXIT_SUCCESS);
}
---
Here is the unexpected behavior while redirecting the 'stdout' stream to a file:
---
$ ./main.out 1>1.txt
$ cat 1.txt
<?xml version="1.0"?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>test</title>
</head>
<body>
<p>test</p>
</body>
</html>
Content-Type: application/xhtml+xml;
---
As you can see above, the string printed with the 'printf' function is shown after the string printed with
the 'xmlSaveToFd' function.
However, it only happens while redirecting the 'stdout' stream to a file.
Indeed, here is what happens when I run the program without redirecting:
---
$ ./main.out
Content-Type: application/xhtml+xml;
<?xml version="1.0"?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>test</title>
</head>
<body>
<p>test</p>
</body>
</html>
---
A workaround is to call the 'fflush' function just after the call to the 'printf' function (see the commented
line in the code above).
But I really don't understand why it is necessary to flush the steam because the '\n' character should
already force the stream to be written on the screen.
Is it a bug in libxml2?
Can someone explain this behavior please?
Thank you.
Best regards.
[Date Prev][
Date Next] [Thread Prev][
Thread Next]
[
Thread Index]
[
Date Index]
[
Author Index]