我正在尝试打印文件的所有内容,但无法将其打印到文件中,但只打印了第一行,建议采取同样的方法。
首先,当我没有使用while循环时,它只打印了一行当我使用while循环时!EOF条件下,它甚至没有进入while循环,因此没有打印任何内容。
static void
processNode(xmlTextReaderPtr reader) {
const xmlChar *name, *value;
FILE *fp = fopen("telemetryOutput.txt", "w+");
name = xmlTextReaderConstName(reader);
if (name == NULL)
name = BAD_CAST "--";
value = xmlTextReaderConstValue(reader);
fprintf(fp, "%sn", "Testing");
// facing issue in this portion:
fprintf(fp, "%d %d %s %d %d",
xmlTextReaderDepth(reader),
xmlTextReaderNodeType(reader),
name,
xmlTextReaderIsEmptyElement(reader),
xmlTextReaderHasValue(reader));
/////
if (value == NULL)
fprintf(fp, "n");
else {
if (xmlStrlen(value) > 40)
fprintf(fp, " %.40s...n", value);
else
fprintf(fp, " %sn", value);
}
}
/**
* streamFile:
* @filename: the file name to parse
*
* Parse and print information about an XML file.
*/
static void
streamFile(const char *filename) {
xmlTextReaderPtr reader;
int ret;
reader = xmlReaderForFile(filename, NULL, 0);
if (reader != NULL) {
ret = xmlTextReaderRead(reader);
while (ret == 1) {
processNode(reader);
ret = xmlTextReaderRead(reader);
}
xmlFreeTextReader(reader);
if (ret != 0) {
fprintf(stderr, "%s : failed to parsen", filename);
}
} else {
fprintf(stderr, "Unable to open %sn", filename);
}
}
int main(int argc, char **argv) {
if (argc != 2)
return(1);
/*
* For creating file
*/
FILE *fptr = fopen("telemetryOutput.txt", "rb+");
char there_was_error = 0;
char opened_in_read = 1;
if(fptr == NULL) //if file does not exist, create it
{
opened_in_read = 0;
fptr = fopen("telemetryOutput.txt", "wb");
if (fptr == NULL)
there_was_error = 1;
}
if (there_was_error)
{
printf("Disc full or no permissionn");
return EXIT_FAILURE;
}
/*
* this initialize the library and check potential ABI mismatches
* between the version it was compiled for and the actual shared
* library used.
*/
LIBXML_TEST_VERSION
streamFile(argv[1]);
/*
* Cleanup function for the XML library.
*/
xmlCleanupParser();
/*
* this is to debug memory for regression tests
*/
xmlMemoryDump();
// File Handling
if (opened_in_read)
printf("The file is opened in read mode."
" Let's read some cached datan");
else
printf("The file is opened in write mode."
" Let's do some processing and cache the resultsn");
return EXIT_SUCCESS;
return(0);
}
#else
int main(void) {
fprintf(stderr, "XInclude support not compiled inn");
exit(1);
}
#endif
I have tried using below method but was unable to get required content
while(!EOF){
fprintf(fp, "%d %d %s %d %d",
xmlTextReaderDepth(reader),
xmlTextReaderNodeType(reader),
name,
xmlTextReaderIsEmptyElement(reader),
xmlTextReaderHasValue(reader));
}
您的逻辑是错误的。最初文件指针位于EOF,因为文件是空的。因此,它不会进入循环本身。如果您必须只打印到文件的一行,请不要在while循环中使用该条件。也可以在附加模式下打开文件,否则它可能会在每次写入时从头开始覆盖