The following code throws a system access violation exception ONLY when called from the command prompt. Why? When run the exception is thrown on line 148 of fstream. This does NOT occur when debugging in VS, but only when I try to run the compiled program from the command prompt, same for an elevated command prompt.
#include <stdafx.h>
#include <iostream>
#include <sstream>
#include <fstream>
#include <windows.h>
using namespace std;
using namespace System;
ifstream::pos_type size;
int filesize;
char * memblock;
int main() {
fstream wfile ( "C:\\Plans\\Plan.txt" , ios::out|ios::ate|ios::app);
if(wfile.is_open())
{
wfile<<"\n";
wfile.close();
}
ifstream file ( "C:\\Plans\\Plan.txt" , ios::in|ios::ate);
if (file.is_open()){
int size = file.tellg();
filesize= size;
memblock = new char [size];
file.seekg (0, ios::beg);
file.read (memblock, size);
file.close();
cout << size << " bytes loaded into memory" << endl;
return 1;
}
else cout << "Unable to open file" << endl;
return 0;
}
You aren’t creating a large enough buffer, because you’re not using
ios::binary. Each'\n'in the file will be expanded to'\r\n'; since you sized the buffer to the number of bytes in the file, it can’t handle the expansion and you’re getting a classic buffer overrun.