Create Read Write Text File with KYLIX

This Article is for the beginner to intermediate developer who wants to read / write / print and erase text file. Hope it will be helpfull for many developers .





Create , Read , Write ,Print , Erase

Text Files With KYLIX





By Rahul Tamrakar





This Article is for the beginner to intermediate developer who wants to read / write / print and erase text file. Hope it will be helpfull for many developers .



Now , I will show you the basic commands for reading and writing . It is very very simple.

General I/O Routines



AssignFile Assigns the name of an external file to a file variable.



In order to start working with text files from KYLIX 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. Unless the file named FileName is in the current directory, we need to provide full path .



Reset Opens an existing file (for reading)

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.



Rewrite Creates and opens a new file (or opens and clears an existing file!)



Rewrite creates a new file (opens the file for output) with the name assigned to OpenFile. 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.



WriteLn Write line into the text file .



The WriteLn command is send individual pieces of information to a file



ReadLn Read line from the text file .



ReadLn to read information line by line from a file.

Eof Returns the end-of-file status. (True implies at end of file)



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

OpenFile.EOF

CloseFile Closes an open file.

Close to close the link of OpenFile.



AssignPrn Assigns file to Printer;







Erase Erases an external file.













All these routines are in the SysUtils unit except " Assignprn " for this u have to add " QPrinters " unit in the unit section.









Why i choose TMEMO with TEXT FILE



The following examples show how to save and load a TMemo from file "the hard way".

You could of course use the SaveToFile and LoadFromFile methods of TStrings, but then you wouldn't learn about text file I/O ! and many programmers mostly have 2 problem



1 How to print TMEMO content and Save into TEXT FILES...

2. How to PLAY WITH TEXT FILE in KYLIX.





In this way u will learn ......



1. How to Save / Retrive TMEMO contents into TEXT FILE.

2. How to print TMEMO content through Programme.

3. how to Create / Write / Read /Print and Erase TEXT FILES.











1. Creating and Writing Content to Text File





Ensures that OutFile will always be closed even if an exception is raised while writing the file.





{ SaveToFile:

  This procedure saves the contents of a Memo to a given file Path and Name

}

procedure SaveToFile(MemoName : TMemo; FileName : string);

var

  OpenFile : TextFile; { The text file }

  Counter : integer; { Loop counter }

begin

  AssignFile(OpenFile, FileName); { Associate OpenFile with Given File Path and name }

  Rewrite(OpenFile); { Open it }

  try

    try

      for Counter := 0 to MemoName.Lines.Count - 1 do

        Writeln(OpenFile, Memoname.Lines[Counter]);



       application.MessageBox('Memo Save into Text File ' + FileName );

    except on E:EInOutError do

      MessageDlg('Save aborted with error: ' + IntToStr(E.ErrorCode)

       , mtError, [mbOK], 0);

    end;

  finally

    CloseFile(OpenFile);

  end;

end;





The above example shows how to catch a file I/O exception and extract the error code from it. Note that it is good form to keep the outer try-finally block in case a non I/O exception is raised.





2. Reading Content from Text File





{ ReadFromFile:

  This procedure read contents from a given file Path Name

}



procedure ReadFromFile(MemoName : TMemo; FileName : string);

var

  OpenFile : TextFile; { The text file }

  Line : string; { The line read in }



begin

  MemoName.Lines.Clear; { Empty the memo }

  AssignFile(OpenFile, FileName); { Associate OpenFile with file name }

  Reset(OpenFile); { Open it without clobbering it }

  try

    try

         while not Eof(OpenFile) do

         begin

                Readln(OpenFile,Line);

                MemoName.Lines.Add(Line);

        end;

    except on E:EInOutError do

      MessageDlg('Can Not Read error: ' + IntToStr(E.ErrorCode)

       , mtError, [mbOK], 0);

    end;

  finally

    CloseFile(openFile);

  end



end;





Finally this example shows how reverse the process of reading text from a file. Note that Readln copies all text up to but not including the end of line marker into the given string. It then skips past the end of line marker to the next line if there is one. If there is no next line then EOF becomes True.



3. Printing with Text File



An advantage of Object Pascal text files that I haven't yet mentioned is that they can be used to send data directly to devices. This example shows how you can send text directly to the printer.



{ PrintMemo:

  This procedure read contents from Memo and print it

}



procedure PrintMemo(MemoName : TMemo; FileName : string);

var

  OpenFile : TextFile; { The text file}

  Counter : integer; { Loop counter }

begin

  AssignPrn(OpenFile); {unit QPrinters Assign text file to PRN }

  Rewrite(OpenFile); { Open it }

  try

    try

            for Counter := 0 to MemoName.Lines.Count - 1 do

                Writeln(OpenFile,MemoName.Lines[Counter]);

    except on E:EInOutError do

      MessageDlg('Can Not Print error: ' + IntToStr(E.ErrorCode)

       , mtError, [mbOK], 0);

    end;

  finally

    CloseFile(OpenFile);

  end;

end;



Note that in this case I am using AssignPrn rather than AssignFile. Having done this you can simply write to the printer as if it was a "normal" text file.



4. Erase Text File



procedure EraseFile(FileName : string);

var



  OpenFile : TextFile; { The text file}

begin

 if FileExists(FileName ) then

  begin

    AssignFile(OpenFile, FileName); { Associate OpenFile with file name }

    try

      Reset(OpenFile); { Open it without clobbering it }

      CloseFile(openfile);

      Erase(Openfile);

      application.MessageBox(FileName + ' ! DELETED ');

    except on E:EInOutError do

      MessageDlg('Can Not ERASE error: ' + IntToStr(E.ErrorCode)

       , mtError, [mbOK], 0);

    end;

  end

 else

       application.MessageBox('ERROR ! ' + FileName + ' ! Not Found');

end;





5. How to get Application Path



{ FilePathName:

  This Function return Application path with text file name

}



function FilePathName : string;

var

Fpath,Fname : string;



begin

{ExtractFilePath() it will return the APPLICATION PATH }



Fpath:=ExtractFilePath(application.ExeName);

Fname :='MyFile.txt';



FilePathName:=Fpath + Fname;



end;







Happy Programming





KYLIX_TEXTFILE.RTF

 

Share this article!

Follow us!

Find more helpful articles: