Login Page - Create Account

Support Board


Date/Time: Thu, 02 May 2024 03:27:19 +0000



Post From: How to read file with sc.ReadFile()?

[2022-05-22 11:42:30]
User431178 - Posts: 412
Here is a modified version, probably not perfect and would certainly need to be modified if the value contained in text file changes.


#include "sierrachart.h"
#include <stdio.h>
#include <stdlib.h>

SCDLLName("ReadLineFromFile")

SCString ReadTextFile(SCStudyInterfaceRef sc, SCString FileLocation)
{
char TextBuffer[1000] = {}; // string size 1k, adjust as needed,
int FileHandle = 1; // File Handle cannot be just an integer numbers, has to be defined first, sc.OpenFile requires int&

//unsigned int *p_BytesRead = new unsigned int(0); // sc.ReadFile() requires unsigned int pointer
// Don't do this, it is not necessary, also, using new without a corresponding delete = memory/resource leak
// see edit below using address of operator (&)

unsigned int bytesRead{ 0 };

sc.OpenFile(FileLocation.GetChars(), n_ACSIL::FILE_MODE_OPEN_EXISTING_FOR_SEQUENTIAL_READING, FileHandle);
sc.ReadFile(FileHandle, TextBuffer, 1000, &bytesRead); // use & operator here
sc.CloseFile(FileHandle);

return TextBuffer;
}

SCSFExport scsf_ReadLineFromFile(SCStudyGraphRef sc)
{
SCSubgraphRef Line1 = sc.Subgraph[0];
SCInputRef PathAndFile = sc.Input[0];

if(sc.SetDefaults)
{
sc.GraphName = "Read Line Value From File";
sc.StudyDescription = "Read Line Value From File";;
sc.DrawZeros = 0;
sc.AutoLoop = 0;
sc.GraphRegion = 0;
sc.ValueFormat = 4;
sc.CalculationPrecedence = LOW_PREC_LEVEL;

Line1.Name = "Line 1";
Line1.DrawStyle = DRAWSTYLE_LINE;
Line1.PrimaryColor = COLOR_CYAN;
Line1.DrawZeros = false;

PathAndFile.Name = "Path and Filename";
PathAndFile.SetPathAndFileName("");

return;
}

float& r_LineValue = sc.GetPersistentFloatFast(0);

if (sc.UpdateStartIndex == 0)
{
r_LineValue = 0.0f;

SCString buffer = ReadTextFile(sc, PathAndFile.GetPathAndFileName());

if (buffer.GetLength() > 0)
{
buffer = buffer.GetSubString(buffer.GetLength() - 1);
r_LineValue = std::strtof(buffer, nullptr);
}
}

for (int index = sc.UpdateStartIndex; index < sc.ArraySize; index++)
Line1[index] = r_LineValue;
}

Testing on chart with 5 days of data, this version had a calculation time of 0ms, whereas the code posted previously had a calculation time of 261ms.