我想通过 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;
最后一行包含以下内容: RapidXML 如何快速读取文件?
最佳答案
你错过了两件事:
在 malloc 上:
缓冲区 = (char*)malloc(sizeof(char)*lSize + 1);//'\0'的位置;
恐惧之后:
缓冲区[lsize]='\0';//终止字符串
您还可以使用fgets()
或std::ifsteam
方法getline
关于c++ - 如何通过 stdio 正确读取文件? C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20730377/