概念是把全部的檔案都先load到記憶體中
並且先掃過檔案,知道elements數,產生靜態陣列
最後再用strtod將記憶體中的char*轉換成double
strtod可以回傳轉換終止的ptr
atod可以轉換,但沒有回傳ptr
//use "rb" can have less problem..
FILE* pFile = fopen("text.asc", "rb");
fseek(pFile, 0, SEEK_END);
int charCount = ftell(pFile);
rewind(pFile);
// allocate memory to open the whole file
char* charBuffer = (char*)malloc(sizeof(char) * charCount);
fread(charBuffer, charCount, 1, pFile);
// get file elements count
for (int i = 0; i < charCount; i++)
{
switch (charBuffer[i])
{
case '\n':
case '\r':
case ' ':
numberCount++;
break;
default:
break;
}
}
fclose(pFile);
// allocate memory to hold the elements
double* xyz = (double*)malloc(sizeof(double) * numberCount);
double* currentXyz = xyz;
char* pNumberEnd = charBuffer;
char* pLastNumber = charBuffer + numberCount;
int line = 0;
// get the elements
while (pNumberEnd < pLastNumber)
{
*(currentXyz++) = strtod(pNumberEnd, &pNumberEnd);
}
沒有留言:
張貼留言