1. Ошибка времени выполнения: «Данный формат пути не поддерживается».
Это самая известная ошибка, которую рано или поздно встречает любой начинающий программист. Взгляните на картинку:
Впервые встретившись с этой ошибкой, можно прийти в недоумение. Файл, из которого мы собираемся читать, на месте. Он доступен и нормально открывается текстовым редактором. Тем не менее, что-то не так. На самом деле, все просто: во время набора текста программы вместо латинской «ЦЭ» была напечатана русская «ЭС». К счастью, такая ошибка единственная в своем роде. Раскладки «qwerty» и «йцукен» имеют совпадение только в одном месте.
2. Ошибка времени выполнения: «Файл не найден».
Еще одна «механическая» ошибка, связанная с использованием процедуры Assign. В принципе, история похожа на рассказанную выше. Автор программы видит, что файл не найден, идет в папку «123» и не понимает: «Как не найден? Вот же он!»
Все просто: вместо нужного вам текстового файла «55.txt» вы создали файл с именем «55.txt.txt» . Этой ошибки не будет возникать, если вы для себя четко раз и навсегда уясните, что такое расширение в имени файла. И вообще, не пользуйтесь проводником в Windows, а работайте в менеджере файлов, например, в Total Commander.
Topic: Using Assign function (Read 2643 times)
Lazarus newby here — did some playing around with an unfinished Delphi application 8 years ago, and have done no programming since, so VERY rusty on Pascal syntax etc. Revisiting the application rewriting it with Lazarus, so lots of research & scouring of examples as I go, however this one escapes me.
A simple routine to read a text file, the contents of which will be used to set the path to my dbase tables (in case the deployment doesn’t allow the path I have chosen during design). I declare a variable as type TextFile :
-
var
-
filePath: TextFile;
and then assign the text file name to it:
-
Assign(filePath, ‘dBpath.txt’);
but the compiler throws up an error of «wrong number of parameters specified for call to «Assign». All info I can find says it only needs the two parameters. Anyone shed any light?
Logged
Hi!
To avoid those mix-ups the assign to a file was changed in Delphi 1 ( ~ 1995) to
assignFile (afile, filename);
So the syntax is
assignFile (afile, filename);
rewrite (afile) or reset(afile);
…..
closeFile(afile)
Winni
Logged
Logged
-
var
-
Filepath:text;
-
s:string;
-
begin
-
Assign(filePath, ‘dBpath.txt’);
-
rewrite(filepath);
-
writeln(filepath,‘test’);
-
flush(filepath); // this depends on platform, do it anyway.
-
close(Filepath);
-
// Assign(filepath,’dBpath.txt’); // this is not necessary
-
reset(filepath);
-
readln(filepath,s);
-
writeln(s);
-
close(filepath);
-
end.
Must indeed be the umptiest time I answered this. Read the manuals….
« Last Edit: March 10, 2020, 01:12:25 pm by Thaddy »
Logged
I actually get compliments for being rude… (well, Dutch, but that is the same)
All info I can find says it only needs the two parameters. Anyone shed any light?
I think a fair question is «where have you been looking?» since if it was FPC or Lazarus documentation (i.e. as distinct from Turbo Pascal or something even older) a fix is in order.
MarkMLl
Logged
MT+86 & Turbo Pascal v1 on CCP/M-86, multitasking with LAN & graphics in 128Kb.
Pet hate: people who boast about the size and sophistication of their computer.
GitHub repositories: https://github.com/MarkMLl?tab=repositories
All info I can find says it only needs the two parameters. Anyone shed any light?
I think a fair question is «where have you been looking?» since if it was FPC or Lazarus documentation (i.e. as distinct from Turbo Pascal or something even older) a fix is in order.
MarkMLl
My example is standard pascal. You do not even need to declare a mode….
And — not to put too fine a point on it — test my code before you answer otherwise your response is useless…
Logged
I actually get compliments for being rude… (well, Dutch, but that is the same)
Thankyou winni & trev — AssignFile & CloseFile did indeed resolve the issue. Very confusing, as although I did see AssignFile used in an example (as well as Assign in another), neither the Lazarus wiki or Free Pascal Reference guide has an entry for AssignFile …..
Logged
Hi!
To make things clear — there is «another» assign in Pascal:
-
var
-
MyBitmap : TBitmap;
-
Img : TImage;
-
….
-
MyBitmap.assign(Img.Picture.Bitmap);
-
…
Winni
Logged
All info I can find says it only needs the two parameters. Anyone shed any light?
I think a fair question is «where have you been looking?» since if it was FPC or Lazarus documentation (i.e. as distinct from Turbo Pascal or something even older) a fix is in order.
MarkMLl
My example is standard pascal. You do not even need to declare a mode….
And — not to put too fine a point on it — test my code before you answer otherwise your response is useless…
Thaddy, why are you responding like that to my posting? It wasn’t even directed at you, it was for OP to try to find out where he was still finding mention of Assign() in the context of file handling.
MarkMLl
Logged
MT+86 & Turbo Pascal v1 on CCP/M-86, multitasking with LAN & graphics in 128Kb.
Pet hate: people who boast about the size and sophistication of their computer.
GitHub repositories: https://github.com/MarkMLl?tab=repositories
[…] it was for OP to try to find out where he was still finding mention of Assign() in the context of file handling.
My guess? In the RTL help, in the reference for unit
System
.
Note that file-handling
Assign
shoudn’t be a problem unless one is calling it inside a method of class which itself has an Assign method. Which is most (all?) classes, hence the
AssignFile
alias. It’s basically a question of scope.
« Last Edit: March 10, 2020, 03:03:45 pm by lucamar »
Logged
Turbo Pascal 3 CP/M — Amstrad PCW 8256 (512 KB !!!)
Lazarus/FPC 2.0.8/3.0.4 & 2.0.12/3.2.0 — 32/64 bits on:
(K|L|X)Ubuntu 12..18, Windows XP, 7, 10 and various DOSes.
Hi!
This might help Centauri with his question about ISO-Pascal.
And Thaddy against his life-threatening allergy with assignfile.
-
system.assign (afile,Filename);
-
reset(afile); { or rewrite }
-
….
-
system.close (aFile);
Winni
Logged
The difference between Assign and Assignfile is a: only uses the system unit and b: has some overloads in case you should want to allow for codepages. Otherwise it is simply an alias for Assign,
So it is not an allergy, but quite often you do not want or need AssignFile. It draws in the objpas unit (because of an object supporting mode) and you do not always want that. I hope that explains it.
Pascal does not know about AssignFile, Object Pascal does…
« Last Edit: March 10, 2020, 04:08:23 pm by Thaddy »
Logged
I actually get compliments for being rude… (well, Dutch, but that is the same)
Note that file-handling Assign shoudn’t be a problem unless one is calling it inside a method of class which itself has an Assign method. Which is most (all?) classes, hence the AssignFile alias. It’s basically a question of scope.
Only classes that derive from
TPersistent
contain the
Assign
method (and of course other, unrelated classes might).
Logged
Не могу понять в чём ошибка(Строка указана)
const
key = 2;
function shifrch(arg: char): char;
var
x: integer;
begin
result := arg;
if ord(arg) > 32 then
begin
x := ord(arg) + key;
if x > 255
then x := x - 255 + 32;
result := char(x);
end;
end;
function deshifrch(arg: char): char;
var
x: integer;
begin
result := arg;
if ord(arg) > 32 then
begin
x := ord(arg) - key;
if x < 255
then x := x + 255 - 32;
result := char(x);
end;
end;
procedure shifrs(arg: string);
var
i: integer;
begin
for i := 1 to length(arg) do
begin
arg[i] := shifrch(arg[i]);
end;
end;
procedure deshifrs(arg: string);
var
i: integer;
begin
for i := 1 to length(arg) do
begin
arg[i] := deshifrch(arg[i]);
end;
end;
procedure shifrf(const kfile: string; tr: boolean);
const
shfile = 'ZasifrF';
var
infile, outfile: text;
s: string;
begin
if tr then
begin
assign(infile, kfile);{Тут пишет: Ошибка времени выполнения: Путь имеет недопустимую форму}
assign(outfile, shfile);
end
else
begin
assign(infile,shfile );
assign(outfile, kfile);
end;
reset(infile);
rewrite(outfile);
while not eof(infile) do
begin
if tr then
begin
readln(infile,s);
shifrs(s);
writeln(outfile,s)
end
else
begin
readln(infile,s);
deshifrs(s);
writeln(outfile,s)
end;
end;
end;
var
tf: boolean;
s: string;
begin
writeln('Введите 1, чтобы шифровать, введите иное, чтобы расшифровать');
readln(s);
tf := s = '1';
if tf then
begin
writeln('Введите шифруемый файл');
readln(s);
end
else
writeln('Введите расшифруемый файл');
readln(s);
if tf then
shifrf(s, tf)
else
shifrf(s, tf);
end.
задан 7 сен 2019 в 18:40
1
У вас в коде как минимум одна ошибка:
if tf then
begin
writeln('Введите шифруемый файл');
readln(s);
end
else
writeln('Введите расшифруемый файл');
readln(s);
Здесь второй вызов ReadLn
выполняется в любом случае. И если вы там просто вводите пустую строку, то в дальнейшем она передаётся в Assign
. Исправьте на:
IF tf THEN
WriteLn('Введите шифруемый файл:')
ELSE
WriteLn('Введите расшифруемый файл:');
ReadLn(s)
ответ дан 7 сен 2019 в 21:48
Ainar-GAinar-G
16k3 золотых знака24 серебряных знака41 бронзовый знак
Группа: Пользователи
Сообщений: 5
Пол: Мужской
Реальное имя: Ярик
Репутация: 0
При работе с файлом мне нужно указать путь к файлу с клавиатуры. В моём варианте assign работает только, если в программе не участвует readln(read). Поиском не пользовался, дабы нет времени. Просто очень срочно. Ребят, прошу помощи.
uses crt;
const N=10; M=15;
type massiv=array[1..N,1..M] of integer;
var a: massiv;
i,v,h,o,b,p,N2,M2,j,t,g,k,l: integer;
s: real;
f,f2: text;
str:string;
ch: char;begin {1}
clrscr;writeln ('Введите размер матрицы вида (M*N; gde N-столбцы (максимальный размер 10*15)');
writeln ('Введите количество столбцов');
repeat
read (N2);
until (N2>=3) and (N2<=10); {часть ввода данных}
writeln ('Введите количество строк');
repeat
read (M2);
until (M2>=1) and (M2<=15);
writeln;begin
writeln ('Куда вывести используемые данные? 1-записать в файл 2-вывести на окно ');
ch:=readkey;
if ch='1' then {сама работа с файлом (запись текста в него, с указанием полного пути, вводимого с клавы}
writeln ('Введите путь к файлу');
read (str);
assign (f2,str);
rewrite (f2);
write (f2,'isxodnaya matriza');close (f2);
end;readln;
readln;
end. {1}
я, думаю, для вас это ламерский вопрос..
B
Well, that’s an example of keeping and downloading. For example, no error treatment is envisaged.program textwrite;
{$APPTYPE CONSOLE}
type
tOption=record
ID: integer;
Name: string[40];
end;
tAuto=record
Mark: string[20];
Model: string[20];
Colour: string[20];
Price: integer;
Options: Array[1..3] of tOption;
end;
procedure WriteAuto(const t: text; const auto: tAuto);
procedure WriteOption(const opt: tOption);
begin
WriteLn(t, opt.id, #9, opt.Name);
end;
var
index: Integer;
begin
WriteLn(t, auto.Mark);
WriteLn(t, auto.Model);
WriteLn(t, auto.Colour);
WriteLn(t, auto.Price);
for index := Low(auto.Options) to High(auto.Options) do
WriteOption(auto.Options[index]);
end;
procedure ReadAuto(const t: text; var auto: tAuto);
procedure ReadOption(var opt: tOption);
var
Text: string;
Tab: Integer;
Code: Integer;
begin
ReadLn(t, Text);
Tab := Pos(#9, text);
val(copy(text, 1, Tab — 1), opt.ID, Code);
opt.Name := Copy(Text, Tab + 1, Length(Text));
end;
var
index: Integer;
begin
ReadLn(t, auto.Mark);
ReadLn(t, auto.Model);
ReadLn(t, auto.Colour);
ReadLn(t, auto.Price);
for index := Low(auto.Options) to High(auto.Options) do
ReadOption(auto.Options[index]);
end;
const
Cars: array [0..1] of tAuto = (
(Mark: ‘Nissan’; Model: ‘Sentra’; Colour: ‘Red’; Price: 100500; Options:
((Id: 1; Name: ‘Pedals’), (Id: 2; Name: ‘Railings’), (Id: 3; Name: »))),
(Mark: ‘Renault’; Model: ‘Logan’; Colour: ‘Blue’; Price: 10600; Options:
((Id: 1; Name: ‘Driver’), (Id: 2; Name: »), (Id: 3; Name: »))));
var
index: Integer;
f: text;
loaded: array [0..1] of tAuto;
begin
// сохранение
AssignFile(f,’sort.txt’);
Rewrite(f);
for index := Low(Cars) to High(Cars) do
WriteAuto(f, Cars[index]);
Close(f);
// загрузка
AssignFile(f,’sort.txt’);
Reset(f);
for index := Low(Cars) to High(Cars) do
ReadAuto(f, loaded[index]);
Close(f);
ReadLn;
end.
The algorithm of work is simple:First, we’re in the cycle for every car. WriteAuto()which keeps every TAuto field in a separate line of the file. It then, in turn, causes each option WriteOption()which retains the option in the same file (for diversity ID and Name are written in the same line shared by the tabulator).For loading, respectively ReadAuto() and ReadOption()♪ ReadOption After reading the line from the file, it is divided into two parts by the tabulation symbol and assigns the values to the relevant tOption fields.The function of Val() converts the row with numbers to number, instead it can be used opt.ID := IntToStr(copy(text, 1, Tab — 1));♪When downloaded from such a file, it is necessary to know exactly how many records it contains (loading range). Well, the number of records can be recorded/read before reading the rest of the data.PS: #9 is the Tab symbol, it is assumed that it does not meet in the name of the Opium.PS: Delphi Pizano, there’s no pure pascal under his hand.