I have the current code that readings a text file into memory:
std::streampos fsize = 0;
std::ifstream file(fileName, std::ios::binary); // open file
if(!file.good()) {
std::cout << "Error opening file";
return 0;
}
// get length of file
file.seekg(0, ios::end);
fsize = file.tellg();
// allocate memory
char *memory = new char[fsize];
// read data as a block
file.seekg (0, ios::beg);
file.read (memory, fsize);
file.close(); // close file
return fsize;
Now i have code that iterates over it. If the line starts with ‘v’ it reads the 3 preceding float values, and same with if it starts with ‘n’, but into different arrays.
char* p = memory; // pointer to start of memory
char* e = memory + fsize; // pointer to end of memory
while (p != e) {
if (memcmp(p, "v", 1) == 0) {
sscanf(p, "v %f %f %f", &a[vI], &b[vI], &c[vI]);
vI++;
} else if (memcmp(p, "n", 1) == 0) {
sscanf(p, "v %f %f %f", &d[nI], &e[nI], &f[nI]);
nI++;
while (*p++ != (char) 0x0A);
}
I know there must be a better/safer way to do this.
I assume you have a text-file there. This can be done a lot simpler. First, don’t open the file in binary-mode, and simply read linewise. The following is a possible implementation:
This code assumes that lines starting with
'v'are well-formed. You can use it like this: