Автор: de1phi | 18.12.2007 в 10:22 | Рубрики: ASCII

Приведу несколько простых функций, позволяющих работать с отдельными словами в строке. Возможно они пригодятся вам для разбивки текстовых полей на отдельные слова (for i := 1 to NumToken do …) с последующим сохранением их в базе данных.

function GetToken(aString, SepChar: string; TokenNum: Byte): string;
{
параметры: aString : полная строка

SepChar : единственный символ, служащий
разделителем между словами (подстроками)
TokenNum: номер требуемого слова (подстроки))
result : искомое слово или пустая строка, если количество слов

меньше значения ‘TokenNum’
} Читать полностью…

Автор: de1phi | в 10:22 | Рубрики: ASCII

Скачивание файла.
Размер: неизвестно (скачено 45%).

var s: String; f: TextFile;
AssignFile(f, ‘D:\\INPUT.TXT);
Reset(f);
while not EOF(f) do
begin
ReadLn(s, f);
ShowMessage(GetField(s, 1)); {The first field\}
ShowMessage(GetField(s, 6)); {The sixth field\}
ShowMessage(GetField(s, 25)); {will return ” if no 25 column…\}
end;
CloseFile(f);

{ ==== This function will return a field from a delimited string. ==== \}
function GetField(InpString: String; fieldpos: Integer): String;
var
c: Char;
curpos, i: Integer;
begin
curpos := 1;
for i := 1 to fieldpos do
begin
result := ”; if curpos > Length(InpString) then Break;
repeat
c := InpString[curpos]; Inc(curpos, 1);
if (c = ‘”‘) or (c = #13) or (c = #10) then c := ‘ ‘;
if c <> ‘,’ then result := result + c;
until (c = ‘,’) or (curpos > Length(InpString))
end;
if (curpos > Length(InpString)) and (i < fieldpos) then result := '';
result := Trim(result);
end;

{ ==== This function will trim a string removing spaces etc. ==== \}
function Trim(inp_str: String): String;
var
i: Integer;
begin
for i := 1 to Length(inp_str) do if inp_str[i] <> ‘ ‘ then Break;
if i > 1 then Delete(inp_str, 1, i - 1);
for i := Length(inp_str) downto 1 do if inp_str[i] <> ‘ ‘ then Break;
if i < Length(inp_str) then Delete(inp_str, i + 1, Length(inp_str));
result := inp_str;
if result = ‘ ‘ then result := ”;
end;

Автор: de1phi | в 10:22 | Рубрики: ASCII

function isAscii(NomeFile: string): Boolean;
const
SETT = 2048;
var
i: Integer;
F: file;
a: Boolean;
TotSize, IncSize, ReadSize: Integer;
c: array[0..Sett] of Byte;
begin
if FileExists(NomeFile) then
begin
{$I-}
AssignFile(F, NomeFile);
Reset(F, 1);
TotSize := FileSize(F);
IncSize := 0;
a := True;
while (IncSize < TotSize) and (a = True) do
begin
ReadSize := SETT;
if IncSize + ReadSize > TotSize then ReadSize := TotSize - IncSize;
IncSize := IncSize + ReadSize;
BlockRead(F, c, ReadSize);
// Iterate
for i := 0 to ReadSize - 1 do
if (c[i] < 32) and (not (c[i] in [9, 10, 13, 26])) then a := False;
end; { while }
CloseFile(F);
{$I+}
if IOResult <> 0 then Result := False
else
Result := a;
end;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
if OpenDialog1.Execute then
if isAscii(OpenDialog1.FileName) then
ShowMessage(’ASCII File’);
end;

Автор: de1phi | в 10:22 | Рубрики: ASCII

В Delphi 1.0 для получения количества записей в ASCII файле (.TXT- и .SCH-файлы) я пользовался свойством RecordCount компонента TTable. В Delphi 2.0 эта функциональность не поддерживается! Я прав или не прав? Во всяком случае как мне получить количество записей, содержащихся в ASCII таблице?

В Delphi 2.0, свойство RecordCount отображается на недокументированную функцию BDE DbiGetExactRecordCount. Данное изменение было сделано для обеспечения правильных величин при работе с “живыми” запросами. Очевидно, данное API по какой-то причине не поддерживает текстовые файлы.

Вы можете обойти эту проблему, вызывая функцию API BDE DbiGetRecordCount напрямую (добавьте BDE к списку используемых модулей):

procedure TForm1.FormKeyUp(Sender: TObject; var Key: Word;
var
RecCount: Integer;
begin
Check(DbiGetRecordCount(Table1.Handle, RecCount);
end;

Автор: de1phi | в 10:22 | Рубрики: ASCII

procedure ReadTabFile(FN: TFileName; FieldSeparator:
Char; SG: TStringGrid);
var
i: Integer;
S: string;
T: string;
Colonne, ligne: Integer;
Les_Strings: TStringList;
CountCols: Integer;
CountLines: Integer;
TabPos: Integer;
StartPos: Integer;
InitialCol: Integer;
begin
Les_Strings := TStringList.Create;
try
// Load the file, Datei laden
Les_Strings.LoadFromFile(FN);

// Get the number of rows, Anzahl der Zeilen ermitteln
CountLines := Les_Strings.Count + SG.FixedRows;

// Get the number of columns, Anzahl der Spalten ermitteln
T := Les_Strings[0];
for i := 0 to Length(T) - 1 do Inc(CountCols,
Ord(IsDelimiter(FieldSeparator, T, i)));
Inc(CountCols, 1 + SG.FixedCols);
Читать полностью…