如何将libtidy的解析输出转换为char *

时间:2011-08-23 14:31:57

标签: c++ tidy

我正在尝试将libtidy用于C ++程序,只需极少的返工。 C ++程序需要在char *中生成(清理)HTML。我正在使用libtidy示例代码但是尝试使用tidySaveString而不是想要使用libtidy自己的缓冲区的tidySaveBuffer。

问题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_)。理想情况下(显然)我不想将文档转储到输出缓冲区,这样我就可以获得大小 - 但是,我还需要找到一种方法来使其工作。

感谢所有帮助..

1 个答案:

答案 0 :(得分:1)

你必须传入缓冲区大小......

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 );