Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to save data to text file?

Status
Not open for further replies.

swee7an

Programmer
Nov 17, 2005
2
US
Hello there,

i've been using C for a while until i decided to use Delphi.

now i am working on a programme in delphi that takes altitude, speed, weight ... etc. and the output it a plane.

i created a menu, and under File i have Open, Save ... etc.
what i am trying to do is to be able to save all of this information to a text file (using File>Save) and reopen it when needed (using File>Open).

i know how to do it using a button, but i want more option like file location and file name.

thanks in advance.
 
where is the data.

if its in a memo or richedit you use
memo1.lines.savetofile('c:\data.txt');

otherwise you need to create the file and write to it.

Assign
In order to start working with text files from Delphi we have to link a file on a disk to a file variable in our program. To create this link we must first declare a variable of type TextFile and then use AssignFile procedure in order to associate a file on a disk with a file variable.

Code:
var
 SomeTxtFile : TextFile;
begin
 AssignFile(SomeTxtFile, FileName)

Note: Unless the file named FileName is in the current directory, we need to provide enough information to identify its path. Be sure that value of a text variable has a legal Windows filename.

Reading information from a Text File
If we want to read back the contest of a file into a string list, our task is easy. Just one line of code will do the job.

Code:
Memo1.Lines.LoadFromFile('c:\autoexec.bat')

On the other hand, to read information from a file line by line, we must open the file for input by using the Reset procedure. The Reset opens the existing file with the name assigned to TextFile variable. An error results if no existing external file of the given name exists.

Once a file is reset, we can use ReadLn to read information from a file:

Code:
var
 SomeTxtFile : TextFile;
 buffer : string;
begin
 AssignFile(SomeTxtFile, 'c:\autoexec.bat');
 Reset(SomeTxtFile);
 ReadLn(SomeTxtFile, buffer);
 Memo1.Lines.Add(buffer);
 CloseFile(SomeTxtFile);
end;

Procedure called ReadLn, reads one line of text from a file then moves to the next line.

After adding one line of text from a file to a memo component SomeTxtFile needs to be closed. This is done by the Close keyword.

Note: We can also use Read procedure to read information from a file. Read works just like ReadLn, except it does not move the pointer to the next line. As the next example shows, we can use multiple variables in each Read statement:

Code:
var
 SomeTxtFile : TextFile;
 buf1,buf2 : string[5];
begin
 AssignFile(SomeTxtFile, 'c:\autoexec.bat');
 Reset(SomeTxtFile);
 ReadLn(SomeTxtFile, buf1,buf2);
 ShowMessage(buf1 + ' ' +buf2);
 CloseFile(SomeTxtFile);
end;

The EOF
Eof is the EndOfFile checking function. We can use this function to make sure that we are not trying to read beyond the end of the file. Let's say we want to display the contest of the file in message boxes - one line at a time, until we get to the end of a file:

Code:
var
 SomeTxtFile : TextFile;
 buffer : string;
begin
 AssignFile(SomeTxtFile, 'c:\autoexec.bat');
 Reset(SomeTxtFile);
 while not EOF(SomeTxtFile) do begin
  ReadLn(SomeTxtFile, buffer);
  ShowMessage(buffer);
 end;
 CloseFile(SomeTxtFile);
end;

Note: It is better to use While loop than an Until loop to take into account the (unlikely) possibility that the file exists but does not contain any data.

Sending information to a Text File
Writing text to a file is as easy as reading text from a file. The WriteLn command is probably the most common way to send individual pieces of information to a file. The following code will read a text from a Memo1 component (line by line) and send it to some newly created text file.

Code:
var
 SomeTxtFile : TextFile;
 i: integer;
begin
 AssignFile(SomeTxtFile, 'c:\MyTextFile.txt');
 Rewrite(SomeTxtFile);
 for i := 0 to (Memo1.Lines.Count - 1) do 
   WriteLn(SomeTxtFile, Memo1.Lines[i]);
 CloseFile(SomeTxtFile);
end;

Depending on the state of the file provided to the Rewrite procedure in the previous example, the Rewrite creates a new file (opens the file for output) with the name assigned to SomeTextFile. If a file with the same name already exists, it is deleted and a new empty file is created in its place. If SomeTextFile is already open, it is first closed and then re-created. The current file position is set to the beginning of the empty file.

Note: Memo1.Lines.SaveToFile('c:\MyTextFile.txt') will do the same.

Sometimes we'll just need to add some text data to the end of an existing file. If this is the case, we'll call Append to ensure that a file is opened with write-only access with the file pointer positioned at the end of the file. Something like:

Code:
var
 SomeTxtFile : TextFile;
begin
 AssignFile(SomeTxtFile, 'c:\MyTextFile.txt');
 Append(SomeTxtFile);
 WriteLn(SomeTxtFile, 'New line in my text file');
 CloseFile(SomeTxtFile);
end;

Be aware
In general, you should always use exception handling when working with files. I/O is full of surprises. Always use CloseFile in a finally block to avoid the possibility of corrupting a user's FAT. All the previous examples should be rewritten as follows:

Code:
var
 SomeTxtFile : TextFile;
 buffer : string;
begin
 AssignFile(SomeTxtFile, 'c:\MyTextFile.txt');
 try
  Reset(SomeTxtFile);
  ReadLn(SomeTxtFile, buffer);
 finally
  CloseFile(SomeTxtFile);
 end;
end;

To be sure that a given file exists we have to use FileExists boolean function. This function will return True if the file exists, Else otherwise. The syntax is

Code:
function FileExists(const FileName: string): boolean




Aaron Taylor
John Mutch Electronics
 
Also check out the TSaveDialog component which allows you to prompt a user for a directory and filename. You can combine this with Aaron's suggestions by replacing the hardcoded filenames with SaveDialog1.Filename. Note: you need to make a call to the TSaveDialog's Execute method and check it is successful before using its' Filename property. The Delphi help explains how to use this component anyhow.

Clive
Runner_1Revised.gif

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"To err is human, but to really foul things up you need a computer." (Paul Ehrlich)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
To get the best answers from this forum see: faq102-5096
 
Do not forget about .ini files which might come in handy
for what you are trying to do:

This will require you to add IniFiles to your uses clause.
You can find the uses clause at the top of unit document
right below interface.

How to use the ini file:
Loading data from an ini file:
Code:
procedure TForm1.Button1Click(Sender: TObject);
var myIni: TIniFile;
var Var1, Var2, Var3: string;
begin
myIni := TIniFile.Create('C:\somedir\myini.ini');
var1 := myIni.ReadString('SectionA','SomeIdent1','DefaultString');
var2 := myIni.ReadString('SectionA','SomeIdent2','DefaultString');
var3 := myIni.ReadString('SectionA','SomeIdent3','DefaultString');
myIni.Free;
end;

the var1, var2 and var3 will hold what is loaded from the ini. Where it says SectionA it will create a group of variables. SomeIdent tell you what you saved there. For example it could be in your case what flight data you are storing there (IE: altitude, airspeed, etc etc). DefaultString is what the value will be if the entry is missing.

Saving to an ini file:
Code:
procedure TForm1.Button2Click(Sender: TObject);
var myIni: TIniFile;
begin
myIni := TIniFile.Create('C:\somedir\myini.ini');
myIni.WriteString('SectionA','SomeIdent1','Your variable1');
myIni.WriteString('SectionA','SomeIdent2','Your variable2');
myIni.WriteString('SectionA','SomeIdent3','Your variable3');
myIni.Free;
end;

This is almost the same as the loading bit. You do not have to declare a save routine as this is automatic. Just make sure the section names and identifiers are the same
as in the loading procedure.

Make sure that you Free; the myIni (or whatever you call it) after using it to not waste memory.

Just remember that .INI files are NOT suitable for saving
HUGE amounts of data.





[bobafett] BobbaFet [bobafett]

Code:
if not Programming = 'Severe Migraine' then
                       ShowMessage('Eureka!');
faq102-5352
 
i really appreciate your help guys. its like a complete reference.

i guess i'll go with the ini files method since i'll need to store no more than 40-50 data numbers.

Ahmed.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top