c++ - 如何通过 stdio 正确读取文件? C++

标签 c++ stdio rapidxml cstdio

我想通过 RapidXML 的 stdio 读取文件。我使用了以下内容:

#include <iostream>
#include <rapidxml.hpp>
#include <stdio.h>
#include <Windows.h>

using namespace rapidxml;

int main(int argc, char** argv)
{
    FILE *pFile;
    pFile = fopen("D:\\ColladaFiles\\sample1.dae", "rb");
    long lSize;
    char *buffer;
    size_t result;

    //if error
    if (pFile == NULL) { fputs("File error", stderr); exit(1); }

    // obtain file size:
    fseek(pFile, 0, SEEK_END);
    lSize = ftell(pFile);
    rewind(pFile);

    // allocate memory to contain the whole file:
    buffer = (char*)malloc(sizeof(char)*lSize);
    if (buffer == NULL) { fputs("Memory error", stderr); exit(2); }

    // copy the file into the buffer:
    result = fread(buffer, 1, lSize, pFile);
    if (result != lSize) { fputs("Reading error", stderr); exit(3); }

    /* the whole file is now loaded in the memory buffer. */

    xml_document<> xdoc;
    xdoc.parse<0>(buffer);

    system("pause");
    return 0;
}

RapidXML 产生了一个错误。因为如果我写缓冲区如下:

std::cout << buffer << std::endl;

最后一行包含以下内容: enter image description here RapidXML 如何快速读取文件?

最佳答案

你错过了两件事:

  1. 在 malloc 上:

    缓冲区 = (char*)malloc(sizeof(char)*lSize + 1);//'\0'的位置;

  2. 恐惧之后:

    缓冲区[lsize]='\0';//终止字符串

您还可以使用fgets()std::ifsteam 方法getline

关于c++ - 如何通过 stdio 正确读取文件? C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20730377/

相关文章:

c++ - 具有动态分配内存的 C++ 对象的参数传递

c++ - sizeof 和表达式?

c - 在 C 中检测 EOF

C++ 暂时重定向或禁用 stdio

c++ - 使用 RapidXML 写入 XML

c++ - 在循环中创建的变量名?

c++ - main() 之前的堆栈溢出异常

node.js - 是否可以推送文本来提示输入?

c++ - RapidXML 节点异常处理

c++ - 使用 RapidXML 读取 XML 节点