Hi, I'm curently creating a command line tool in VC++ 2008 Express Edition for myself which requires reading many files and merging them together. Everything is OK and during debugging (F5) there is not a single problem, but at run time (ctrl+F5) a problem with fread occurs at the same location each time. It reads many files without any problem and suddenly it stops at one file (each time the same one) and shows windows error dialog.
Document *load(string fileName){
char *buffer;
FILE *pFile;
long lSize;
size_t result;
string strBuff;
errno_t err;
Document *document = new Document();
err = fopen_s ( &pFile, fileName.c_str() , "rb" );
strBuff = "Can't read file \""+fileName+"\"!";
if (err) {fputs (strBuff.c_str(), stderr); exit (1);}
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+1));
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. */
// Here occurs the error. File has been read, but buffer is clear,
// strBuff.assign crashes.
strBuff.assign(buffer);
free (buffer);
// terminate
fclose (pFile);
return parse(strBuff, document);
}
As you can see from my code, all checks went ok, but for some reason, there is nothing in buffer. I've tried to find out maximal file size I'm going to read and it worked, but then the application is much slower (because of the conversion to string object). and it doesn't explain why it occurs. I would like to know, what is doing this error.