我正在尝试通过最少的工作使libtidy进入C ++程序。 C ++程序需要以char *格式生成(清除)的HTML。我正在使用libtidy示例代码,但尝试使用tidySaveString而不是tidySaveBuffer,后者想要使用libtidy自己的缓冲区。
问题1是我似乎找不到一种(明智的)方法来确定需要为我的缓冲区分配的大小,在libtidy文档中似乎没有明显的迹象。
问题2是,当我使用一种不明智的方法来获取大小(将其放入tidyBuffer并获取该大小)然后分配我的内存并调用tidySaveString时,总是会出现-ENOMEM错误。
这是我正在使用的改编代码:
.
.
.
char *buffer_;
char *cleansed_buffer_;
.
.
.
int ProcessHtml::Clean(){
// uses Libtidy to convert the buffer to XML
TidyBuffer output = {0};
TidyBuffer errbuf = {0};
int rc = -1;
Bool ok;
TidyDoc tdoc = tidyCreate(); // Initialize "document"
ok = tidyOptSetBool( tdoc, TidyXhtmlOut, yes ); // Convert to XHTML
if ( ok )
rc = tidySetErrorBuffer( tdoc, &errbuf ); // Capture diagnostics
if ( rc >= 0 )
rc = tidyParseString( tdoc, this->buffer_ ); // Parse the input
if ( rc >= 0 )
rc = tidyCleanAndRepair( tdoc ); // Tidy it up!
if ( rc >= 0 )
rc = tidyRunDiagnostics( tdoc ); // Kvetch
if ( rc > 1 ) // If error, force output.
rc = ( tidyOptSetBool(tdoc, TidyForceOutput, yes) ? rc : -1 );
if ( rc >= 0 ){
rc = tidySaveBuffer( tdoc, &output ); // Pretty Print
// get some mem
uint yy = output.size;
cleansed_buffer_ = (char *)malloc(yy+10);
uint xx = 0;
rc = tidySaveString(tdoc, this->cleansed_buffer_,&xx );
if (rc == -ENOMEM)
cout << "yikes!!\n" << endl;
}
if ( rc >= 0 )
{
if ( rc > 0 )
printf( "\nDiagnostics:\n\n%s", errbuf.bp );
printf( "\nAnd here is the result:\n\n%s", cleansed_buffer_ );
}
else
printf( "A severe error (%d) occurred.\n", rc );
tidyBufFree( &output );
tidyBufFree( &errbuf );
tidyRelease( tdoc );
return rc;
}
它从输入缓冲区(buffer_)读取要清除的字节,我真的需要(cleansed_buffer_)中的输出。理想情况下(显然),我不想只是将文档转储到输出缓冲区中,以便获得大小-而且,我还需要找到一种使之起作用的方法。
感谢所有的帮助。
最佳答案
您必须传递缓冲区大小...
uint yy = output.size;
cleansed_buffer_ = (char *)malloc(yy+10);
uint xx = yy+10; /* <---------------------------------- HERE */
rc = tidySaveString(tdoc, this->cleansed_buffer_,&xx );
if (rc == -ENOMEM)
cout << "yikes!!\n" << endl;
或者,您可以通过以下方式获得尺寸:
cleansed_buffer_ = (char *)malloc(1);
uint size = 0
rc = tidySaveString(tdoc, cleansed_buffer_, &size );
// now size is the required size
free(cleansed_buffer_);
cleansed_buffer_ = (char *)malloc(size+1);
rc = tidySaveString(tdoc, cleansed_buffer_, &size );
关于c++ - 如何从libtidy解析输出到char *,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7162706/