Da black ninja
Da black ninja

Reputation: 359

Read specific line from TextFile

Assuming that I have a text file and inside it (in the middle or something) there is the following lines :

My name : Someone

My age : 17

My School : Harvard

There is no specific line number for them (random) and It's not duplicated ("My name" only shows one time , My age too etc ...)

It's not what I'm looking for exactly but I thought it should read that specific line but it's not (It's reading the whole file) :

AssignFile(myFile, 'C:\Users\boss\Desktop\dude.txt');
myWord := 'My name : Someone';
Reset(myFile);

while not Eof(myFile) do
begin
  readln(myFile, myWord);
  writeln(myWord);
end;

CloseFile(myFile);

This is reading the whole Textfile as I stated , I was just trying to get something working to manipulate it but I couldn't .

I want to read the whole line after "My name" which means the name won't be the same everytime .

Upvotes: 1

Views: 5859

Answers (2)

MBo
MBo

Reputation: 80177

Cleaning my crystal ball... Probably you need something like this code:

readln(myFile, myWord);
if Pos('My name:', myWord) = 1 then
  Writeln(myWord);

Upvotes: 3

MartynA
MartynA

Reputation: 30715

If I follow what you are wanting to do, it's actually simple.

Suppose you have

var
  ALine,
  StartOfLineToFind,
  AValue : String;
  P : Integer;

  [...]
  StartOfLineToFind := 'My name :';

then in your loop do

    readln(myFile, ALine);
    if Pos(StartOfLineToFind, ALine) = 1 then begin  // see if the line starts with the label you're looking for
      AValue := Copy(ALine, Length(StartOfLineToFind), Length(ALine) - Length(StartOfLineToFind);  //  Copy the rest of the line after the label
      AValue := Trim(AValue);  //  remove the leading and trailing spaces
      writeln(AValue);
    end;

Upvotes: 3

Related Questions