View Full Version : Reading from a file line by line.
groog
10-21-2010, 02:40 AM
How can I read from a file line by line and add it to a string array. I've got something that looks like this-
x, y, i, k: integer;
fileNum, fileSize: integer;
fileString: String;
urlsArray: Array of String;
procedure GetUrls;
begin
fileNum := OpenFile('url.txt', true);
fileSize := FileSize(fileNum);
ReadFileString(fileNum, fileString, fileSize);
end;
but I get this error:
[Error] (12:23): Type mismatch at line 11
Compiling failed.
which would be this line
fileSize := FileSize(fileNum);
But this isn't just a "what's wrong with this code" question. Is this the right way to do it? How should I do it?
function GetURLs(Filename : string) : TStringArray;
var
FileNum, h, i : integer;
s : string;
begin
FileNum := OpenFile(Filename, true);
ReadFileString(FileNum, s, FileSize(FileNum));
CloseFile(FileNum);
result := Explode(chr(10), s);
h := high(result);
for i := 0 to h do
Writeln(result[i]);
end;
begin
GetURLs('C:\url.txt');
end.
ZephyrsFury
10-21-2010, 04:28 AM
ReadFileString gives you a single string with the entire contents of the file.
function GetURLs(Filename : string) : TStringArray;
var
FileNum, h, i : integer;
s : string;
begin
FileNum := OpenFile(Filename, true);
ReadFileString(FileNum, s, FileSize(FileNum));
CloseFile(FileNum);
result := Explode(chr(10), s);
h := high(result);
for i := 0 to h do
Writeln(result[i]);
end;
begin
GetURLs('C:\url.txt');
end.
In other words this function Explodes a string into an array of string by separating the string every time chr(10) or the New Line Feed character is found.
If chr(10) doesn't work try chr(13) - I can't remember which one ends up working.
i luffs yeww
10-21-2010, 05:51 AM
chr(10)+chr(13) should solve all problems. :)
Zyt3x
10-21-2010, 06:49 AM
chr(10)+chr(13) should solve all problems. :)Only in windows
i luffs yeww
10-21-2010, 07:03 AM
I'll assume he's using Windows.. :p
groog
10-21-2010, 07:13 PM
This still give me a type mismatch error though. It's this right here-
FileSize(FileNum)
Wizzup?
10-21-2010, 07:34 PM
Pascal is case insensitive.
Your variable name is the same as the function name.
anonymity
10-21-2010, 11:42 PM
Keeping semi on subject * Not to hijack...
How does one:
- WriteFileString(fileName, 'text and what not');
enter to a new line?
- WriteFileString(fileName, 'text and what not'+chr(10)+chr(13));
Does not work.
Use AppendFile.
Edit:
var
FileNum : integer;
begin
FileNum := AppendFile('C:\blahblah.txt');
WriteFileString(FileNum, Chr(13) + chr(10) + 'new line');
CloseFile(FileNum);
end. etc.
Powered by vBulletin® Version 4.2.1 Copyright © 2024 vBulletin Solutions, Inc. All rights reserved.