Loading file

This is the forum for miscellaneous technical/programming questions.

Moderator: 2ffat

Post Reply
simon696
Posts: 1
Joined: Wed Nov 18, 2020 8:29 am

Loading file

Post by simon696 »

Hello, i have to write a simple decoder and I don't know how to start in builder. Should I use fopen to load txt or it's named differently in rad?
HsiaLin
BCBJ Master
BCBJ Master
Posts: 343
Joined: Sun Jul 08, 2007 6:29 pm

Re: Loading file

Post by HsiaLin »

This is how to open a file per the Help example code:

Code: Select all

void __fastcall TestFileOpen()
{
  int iFileHandle;
  int iFileLength;
  int iBytesRead;
  PAnsiChar pszBuffer = 0;
  String Path = L"C:\\Temp\\readme.txt";

  try
  {
	iFileHandle = FileOpen(Path, fmOpenRead);

	if (iFileHandle > 0)
        {
            iFileLength = FileSeek(iFileHandle, 0, 2);
	    FileSeek(iFileHandle, 0, 0);
	    pszBuffer = new AnsiChar[iFileLength + 1];
	    iBytesRead = FileRead(iFileHandle, pszBuffer, iFileLength);
	    FileClose(iFileHandle);
            ShowMessage(pszBuffer);
            delete[] pszBuffer;
	}
	else
	{
	    Application->MessageBox(L"Can't perform one of the following file operations: Open, Seek, Read, Close.", L"File Error", IDOK);
	}
  }
  catch(...)
  {
	Application->MessageBox(L"Can't perform one of the following file operations: Open, Seek, Read, Close.", L"File Error", IDOK);
	delete [] pszBuffer;
  }

}
or use the fopen method:

Code: Select all

   FILE *fp;
   char *databuff = {0};

   if(NULL == (fp = fopen("c:\\temp\\readme.txt", "r")))
   {
     ShowMessage(L"Problem opening file.");
     fclose(fp);
     return;
   }

   long pos, len;
   pos = ftell(fp);
   fseek(fp, 0L, SEEK_END);
   len = ftell(fp);
   fseek(fp, pos, SEEK_SET);
   databuff = new char[len + 1];
   fread(databuff, len, 1, fp);
   fclose(fp);
   ShowMessage(databuff);
   delete[] databuff;
rlebeau
BCBJ Author
BCBJ Author
Posts: 1759
Joined: Wed Jun 01, 2005 3:21 am
Location: California, USA
Contact:

Re: Loading file

Post by rlebeau »

simon696 wrote: Thu Nov 26, 2020 9:41 am Hello, i have to write a simple decoder and I don't know how to start in builder.
What don't you know about it exactly? Can you be more specific?
simon696 wrote: Thu Nov 26, 2020 9:41 am Should I use fopen to load txt or it's named differently in rad?
fopen() will work fine, though that is how to handle files in C. In C++, prefer to use the standard std::(i)fstream class instead. Or the RTLs own file I/O classes/routines, like TStringList, TFileStream, TStreamReader, TFile, etc. There are MANY different ways to do file I/O in C++. Use whatever works best for your particular needs.
Remy Lebeau (TeamB)
Lebeau Software
Post Reply