Why didn't work the erase and rename? - pascal

I do laboratory work and i need to convert original file by a certain algorithm. Here is my code:
var f1,f2: text;
procedure rounds(var f1, f2: text);
var a: real;
begin
while not EoF(f1) do
begin
read(f1, a);
write(f2, a:0:1, ' ');
end;
end;
begin
assign(f1, './lab.txt');
reset(f1);
assign(f2, './temp'); rewrite(f2);
rounds(f1,f2);
close(f1);
close(f2);
Erase(f1);
rename(f2, 'lab.txt');
end.
Why not deleted f1 and f2 is not renamed?
And I can use only sequential files

Make sure that your files are not opened by any application. From the FreePascal documentation:
Erase removes an unopened file from disk. The file should be assigned with Assign, but not opened with Reset or Rewrite.
Program EraseDemo;
Var MyFile: Text;
begin
Assign(MyFile, 'demo.txt');
Rewrite(MyFile);
Writeln(MyFile, 'Lorem Ipsum dolor est');
close (MyFile);
Erase(MyFile);
end.
Rename changes the name of the assigned file F to S. F must be assigned, but not opened.
Program RenameDemo;
Var MyFile: Text;
begin
Assign(MyFile, paramstr(1));
Rename(MyFile, paramstr(2));
end.

Related

write a number into a file

I made a program to put a number in a file. But the file don't show that number(i'mean my code is working but when open the file i created he doesn't show the number.
Here is the code:
Program firstfich;
Uses Wincrt;
Type fich = file Of Integer;
Var f: fich;
x: Integer; {start }
Begin
Assign(f,'C:\a progremming works bac\first bac programe\kill.dat');
Rewrite(f);
x := 47;
Write(f,x);
Close(f);
End.
If you want to see "47" when you open the file in a text editor, you should not create a file containing the byte 47 (which is the ASCII code for the solidus character "/").
Instead, you should create a file containing the bytes 52 and 55, which are the ASCII codes for the characters "4" and "7", respectively.
You should read about how text files are represented in computer memory. See, e.g., the Wikipedia article on character encodings.
Now, to create a file containing the bytes 52 and 55, you just write the string "47" to the file (all code is in Delphi, a modern Pascal implementation -- if you are using some other Pascal implementation, you might need to modify the code slightly):
program Project1;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils;
var
f: text;
begin
try
try
AssignFile(f, 'D:\number.txt');
Rewrite(f);
Write(f, '47');
CloseFile(f);
except
on E: Exception do
Writeln(E.Message);
end;
finally
Writeln('Done.');
Readln;
end;
end.
This will create a file that contains two bytes: 52 and 55. A text editor will display the characters "4" and "7" (assuming ASCII).
On the contrary, if you would create a file that contains only the byte 47, a text editor would display the solidus character ("/", assuming ASCII).
If you want to see the actual bytes in a file, you shouldn't open it in a text editor, but in a hex editor. I encourage you to download a hex editor and play around with these concepts to learn more about them.
Update, in response to comment: If you insist on writing bytes manually, using old Pascal I/O, the following works in Delphi:
program Project1;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils;
var
b: Byte;
f: file;
begin
try
try
AssignFile(f, 'C:\Users\Andreas Rejbrand\Desktop\number.txt');
Rewrite(f, 1);
b := 52; // Or, better: Ord('4')
BlockWrite(f, b, 1);
b := 55; // Or, better: Ord('7')
BlockWrite(f, b, 1);
CloseFile(f);
except
on E: Exception do
Writeln(E.Message);
end;
finally
Writeln('Done.');
Readln;
end;
end.
Still, this is a horrible way of creating a text file containing the number "47"; it should only be considered for educational purposes. To see alternatives to old Pascal I/O, check out https://stackoverflow.com/a/58298368/282848.
program numbertofile;
var
f: TextFile;
x: Integer;
begin
assign(f, 'kill.dat');
rewrite(f);
x := 47;
write(f, x);
close(f);
end.
Just make your file a text file and your integer will be saved in the file the way you expect it to. Just set your file to a text variable like this:
Var f: text;
x: Integer; {start }
Begin
Assign(f,'C:\a progremming works bac\first bac programe\kill.dat');
Rewrite(f);
x := 47;
Write(f,x);
Close(f);
End.
note the write will not put a carriage return or linefeed after the line. if you want numbers on different lines use writeln instead of write.
Writeln(f,x);

how do I free memory of these .txt files

Working with TXT files I've been seeing a message lately "cannot create file ('c:\01.txt') the process cannot acess the file because it is being used by another process" how do I free memory of these .txt files?
I have this code by Mr. Nice and when i trying to change or add new using: ListBox1.Items.savetofile('01.txt');
"cannot create file ('c:\01.txt') the process cannot acess the file because it is being used by another process"
var
path: string;
SR: TSearchRec;
tempFile: TextFile;
line: string;
begin
path:= 'C:\my all txt\';
if FindFirst(path + '*.txt', faAnyFile, SR) = 0 then
begin
repeat
if (SR.Attr <> faDirectory) then
begin
AssignFile(tempFile, path + SR.Name);
Reset(tempFile);
while not Eof(tempFile) do
begin
Readln(tempFile, line);
ListBox1.Items.Add(line);
end;
end;
until FindNext(SR) <> 0;
FindClose(SR);
end;
end;
You never close files after you're finished with them. You need to use CloseFile once you've reached Eof(tempfile):
while not Eof(tempfile) do
begin
Readln(tempfile, line);
ListBox1.Items.Add(line);
end;
CloseFile(tempfile);

Reading record from a text file into array in Pascal

1.this is my code i want to read a record from a text file into array in pascal my program is about making a hotel helper and i already have a text file with the data of the hotel then i should read it from the text file and store it in array .. but i am facing error 103 exit code (file not open).... any help Please . :)
program Hotel1(input,output);
const max =10; MaxFloor =10;
type
Date = record
day :1..31;
month:1..12;
year:integer;
end;
Booking = record
Guest:string[20];
S_Date:date;
E_date:date;
end;
Booking_Mat= array[1..max] of Booking;
History_Booking = record
B_num:integer;
B_Mat:Booking_Mat;
end;
Room = record
Num:integer;
Bed_num:integer;
Price:integer;
Status:Boolean;
H:History_Booking;
end;
Data = record
Ro:Room;
m:integer;
end;
Data_mat= array [1..max] of Data;
Procedure Read_Data(filename:string; var table:Data_mat);
var df:text; i,j :integer;
n,m,num,GN:integer;
Bed_num,Price:integer;
f:text;
s,e:Date;
Gname:string[20];
ok:boolean;
a:Data_mat;
c:char;
Begin
writeln('Reading ',filename,' records into array.... ');
assign(df,filename);
reset(df);
i:=0;
while (not eof) do
begin
i:=i+1;
Read (f,num);
a[i].Ro.num:=num;
Read (f,Bed_num);
a[i].Ro.Bed_num:=Bed_num;
Read (f,Price);
a[i].Ro.Price:=Price;
Read(f,c);
if (c ='Y') then
a[i].Ro.status:= true
else
a[i].Ro.status:= false;
readln;
End; {while eof}
close(df);
End; {Read_Data}
You've declared two variables of type Text, (df and f) in your var block.
You open df with these lines:
assign(df,filename);
reset(df);
You then read from f (which is not the file you opened above) in several lines, such as this one:
Read (f, num);
It's interesting to note that you actually manage to close the file you really opened, even though you never use it in your loop:
close(df);
The solution to all of these issues is to delete the declaration of either f or df, and then fix the compiler errors you get by correcting the code to use the remaining text variable. (Two important lessons here are
Only declare the variables you actually need.
Use the variables you declare.
Your loop is also invalid, because you're using while not eof with no file provided for which to test the end. Your loop should read while not Eof(df) do instead.
It's also much better to follow the typical naming convention of prefixing types with a T. It makes it clear that it's a type and not a variable, and allows you to read the code more easily. For instance, I'd change your definition of Data to TRoomData, and change the other type declarations accordingly. Here's an example - note that TRoomData now has a field (member) named Room of type TRoom:
TRoomData = record
Room: TRoom;
m: Integer;
end;
TRoom is defined as
TRoom = record
Num: Integer;
Bed_num: Integer;
Price: Integer;
Status: Boolean;
H: THistory_Booking;
end;
And so forth. This allows you to write code more clearly:
var
RoomData: TRoomData;
begin
RoomData.Room.Num := 1;
RoomData.Room.Price := 50;
// etc.
end;
With all that being said, your file does not contain text, and therefore you're using the wrong file type by using df: Text in the first place. You should use a File of TRoomData, allowing you to read and write entire records at a time. Here's an example of doing so:
var
DF: File of TRoomData;
RoomData: TRoomData;
i: Integer;
const
DataFileName = 'D:\TempFiles\RoomData.dat';
Writing it:
// Put some data into the record
RoomData.Room.Num := 1;
RoomData.Room.Bed_num := 1;
RoomData.Room.Price := 40;
RoomData.Room.Status := True;
RoomData.Room.H.B_num := 1;
for i := 1 to Max do
begin
RoomData.Room.H.B_Mat[1].Guest := Format('Guest %d', [i]);
RoomData.Room.H.B_Mat[1].S_Date.Year := 2014;
RoomData.Ro.H.B_Mat[1].S_Date.Month := i;
RoomData.Ro.H.B_Mat[1].S_Date.Day := i;
end;
// Write it out to the file
AssignFile(DF, DataFileName);
try
Rewrite(DF);
Write(DF, RoomData);
finally
CloseFile(DF);
end;
Reading it back in:
AssignFile(DF, DataFileName);
try
Reset(DF);
Read(DF, RoomData);
finally
CloseFile(DF);
end;
(Or, better yet: If the version of Pascal you're using supports it, move away from the old file I/O routines and start using TFileStream instead.)
Last but not least, learn to properly format your code. It makes it much easier to debug and maintain, and it's much easier to read when you can follow the execution path clearly.

Different result of the program than was expected, maybe because of index of arrays

i have to do the following thing.
Make a program in Pascal that after has read a text with a list of nums., it will return the numb. of the nums that appear less than one times in the text.
The text that will be read from the program should be like that.
In the first line there are two nums. seperated by a space, n and m. N is the number of nums that exist, like if the text contains the numbers 1,2,3,4, n is 4 (1..n). M is how many lines follow. Every line has a couple of nums, a,b, (1=b) a and b are separated by a space.
The file that the program will make will have written on it a num., that says how many nyms are appeared less than two tims in the text.
All the nums. are Integer.
0=
I have finished it, but the problem is that at the new text that p has to be written, p is always 1, For me the problem is at the place that i have the bold letters, it might be because i in count and i in a arrays are different, how can i correct this???
Thank you in advance.
program MyProgr;
var
F: text;
t:Textfile;
a,count:array of Integer;
b:Integer;
i,int:Integer;
countnums:Integer;
n,m:String;
lin,nums:Integer;
Small,Big:Integer;
procedure DoWhatEver(S: string);
begin
val(s,int);
Write(s,' ');
for i:=Small to Big do
if (a[i]=int) then
count[i]:=count[i]+1;
end;
procedure FilltheArray;
begin
for i:=Small to Big do
a[i]:=i+1 ;
end;
procedure ProcessString;
var
Strng, S: string;
Last, P: integer;
begin
readln(F,Strng);
Last:=0;
while Last<length(Strng) do
begin
P:=Last+1;
while (P<=length(Strng)) and (Strng[P]<>' ') do
inc(P);
S:=copy(Strng,Last+1,(P-Last-1));
DoWhatEver(S);
Last:=P;
end
end;
procedure ProcessStringA;
var
Strng: string;
Last, P: integer;
begin
readln(F,Strng);
Last:=0;
while Last<length(Strng) do
begin
P:=Last+1;
while (P<=length(Strng)) and (Strng[P]<>' ') do
inc(P);
n:=copy(Strng,Last+1,(P-Last-1));
Val(n,nums);
Last:=P;
end
end;
procedure ProcessStringB;
var
Strng: string;
Last, P: integer;
begin
readln(F,Strng);
Last:=0;
while Last<length(Strng) do
begin
P:=Last+1;
while (P<=length(Strng)) and (Strng[P]<>' ') do
inc(P);
m:=copy(Strng,Last+1,(P-Last-1));
Val(m,lin);
Last:=P;
end
end;
begin
assign(F,'myfile.txt');
reset(F);
ProcessStringA;
Writeln(nums);
ProcessStringB;
Writeln(lin);
setlength(a,nums);
Small:=Low(a);
Big:=High(a);
for i:= Small to big do
count[i]:=0;
FillTheArray;
while not eof(F) do
ProcessString;
for i:=Small to Big do
begin
if count[i]=2 then
countnums:=countnums+1;
end;
Close(f);
Assign(t,'fileout.txt');
Rewrite(t);
Writeln(t,countnums);
close(t);
end.

Reading from text file into list in FreePascal

I have a text file including:
John###198cm###90kg###19age
Tom###120cm###34kg###8age
And I want to read them from file into two lists in FreePascal.
I have tried to use LoadFromFile function, which should make a line into list, but it is not working for me.
This is a variation of your question Reading from file FreePascal.
Here is an example using ReplaceStr() to convert the ### characters into a CR LF pair.
When assigned to the text property of a new list, it will be splitted into items.
Uses
StrUtils;
procedure HandleText;
var
i : Integer;
sSourceList : TStringList;
sExpandedList : TStringList;
begin
sSourceList := TStringList.Create;
sExpandedList := TStringList.Create;
try
sSourceList.LoadFromFile('MySource.txt');
for i := 0 to sSourceList.Count-1 do begin
sExpandedList.Text := ReplaceStr(sSourceList[i],'###',#13#10);
// Do something with your lists
// sExpandedList[0] = 'John' etc ...
end;
finally
sSourceList.Free;
sExpandedList.Free;
end;
end;

Resources