我有一个用C / C ++编写的示例程序,它将文本文件读入内存。在尝试解析此文件时(不是此示例的一部分),我在文件末尾附近发现了大量垃圾。调查这一点我发现在将大文件读入内存时存在一些问题;小尺寸文本文件不会发生此问题。这是我的代码:
#include <conio.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
using namespace std;
char* readFile_(char* fname)
{
char* rv=NULL;
int bytes=0;
FILE* pfile = NULL;
pfile = fopen( fname, "r" );
if ( pfile )
{
fseek(pfile, 0, SEEK_END);
bytes = ftell(pfile);
fseek(pfile, 0, SEEK_SET);
rv = new char[bytes+1];
memset(rv,0,bytes+1);
fread( rv, bytes, 1, pfile );
fclose(pfile);
}
return rv;
}
int main(int argc, char **argv)
{
char* filebuffer = NULL;
filebuffer = readFile_( "mv2.txt" );
FILE* pfile = fopen("op.txt", "w");
int len = strlen(filebuffer);
fwrite( filebuffer, len, 1, pfile );
fclose(pfile);
delete[] filebuffer;
return 0;
}
供参考,文件在此处托管:
mv2.txt文件:https://gist.github.com/anonymous/bb101393729d3ada944f
op.txt文件:https://gist.github.com/anonymous/93595c83ad62e40d0f0a
任何人都可以突出显示出什么问题吗?
编辑:我使用的是Windows(Windows 7操作系统)
编辑2:感谢大家帮助我找到问题,这里是基于您的一些反馈的更新代码,这似乎解决了我的问题,即使对于一些非常大的文本文件:
#include <conio.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
using namespace std;
char* readFile_(char* fname)
{
char* rv=NULL;
long bytes=0;
FILE* pfile = NULL;
pfile = fopen( fname, "rb" );
if ( pfile )
{
fseek(pfile, 0, SEEK_END);
bytes = ftell(pfile);
fseek(pfile, 0, SEEK_SET);
rv = new char[bytes+1];
memset(rv,0,bytes+1);
fread( rv, bytes, 1, pfile );
fclose(pfile);
}
return rv;
}
int main(int argc, char **argv)
{
char* filebuffer = NULL;
filebuffer = readFile_( "mv2.txt" );
FILE* pfile = fopen("op.txt", "wb");
int len = strlen(filebuffer);
fwrite( filebuffer, len, 1, pfile );
fclose(pfile);
delete[] filebuffer;
return 0;
}
答案 0 :(得分:2)
通过包含conio.h,我可以假设你在Windows上。在Windows中,如果不使用二进制模式读取,在这种情况下会遇到问题。我会尝试使用&#34; rb&#34;打开文件。作为模式。
FILE* pfile = NULL;
pfile = fopen( fname, "rb" );