本文整理自网络,侵删。
首先通过一个例子来展示pascal读写txt文件的方式:
Program Salaries;Var F:Text; Salary,max:integer; Name:String[20]; MaxName:String; Sex:0..1;Begin Max:=0; Assign(F,'E:\Exam\Salary.txt'); Reset(F); While not Eof(F) Do Begin ReadLn(F,Name,Sex,Salary); If (Sex=1) and (Salary>Max) then Begin Max:=Salary; MaxName:=Name; EndEnd;
Close(F); Writeln; WriteLn('The highest ladis salary is for Mrs. ',MaxName,'By Value:',Max); Writeln; Writeln; Writeln; Writeln; WriteLn('Press Enter To Exit'); ReadLnEnd.运行代码之前,在你的E:\Exam\,放进去一个Salary.txt文件.txt文件的内容如下,使用空格或者tab分隔一下:
Peter 0 3500Helena 1 2000John 0 0Natalia 1 7000Frank 0 7100运行程序,你会发现:这个程序计算出了女性员工中的工资最高者。解释: .txt文件中,1代表女性,0代表男性。代码中的eof 的意思是:end of file。Assign是分配,赋值的意思。
创建txt文件下面做一件最简单的事情,创建一个txt文件,往里面写一些东西。请运行下面的代码:
Program Lesson9_Program2;Var FName, Txt : String[200]; UserFile : Text; Begin FName := 'PASCAL_Textfile'; Assign(UserFile,'C:\'+FName+'.txt'); {assign a text file} Rewrite(UserFile); {open the file 'fname' for writing} Writeln(UserFile,'PASCAL PROGRAMMING'); Writeln(UserFile,'要是你有啥不明白的,'); Writeln(UserFile,'请记得仔细阅读我在简书上写的文章哦:'); Writeln('Write some text to the file:'); Readln(Txt); Writeln(UserFile,''); Writeln(UserFile,'The user entered this text:'); Writeln(UserFile,Txt); Close(UserFile);End.运行完毕,请你到自己的C盘下面,找到你刚刚创建的文件:PASCAL_Textfile.txt看看。修改代码,自己继续尝试10分钟,让自己熟悉这个代码。
重写txt文件Var UFile : Text;Begin Assign(UFile,'C:\PASCAL_Textfile.TXT'); ReWrite(UFile); Writeln(UFile,'How many sentences, ' + 'are present in this file?'); Close(UFile);End.在原来的txt文件后面,追加(append)内容:Var UFile : Text;Begin Assign(UFile,'C:\PASCAL_Textfile.TXT'); Append(UFile); Writeln(UFile,'append: hahahahaha, '+ 'oh my gooooooooooooood'); Close(UFile);End.重复执行上述的代码,你会发现,C:\PASCAL_Textfile.txt文件后面会一次又一次追加上新的内容:
append: hahahahaha, oh my gooooooooooooood删除文件Var UFile : Text; { or it could be of 'file' type}Begin Assign(UFile,'C:\\PASCAL_Textfile.txt'); Erase (UFile); End.此时你会发现文件被删除了。
最后,请完成下面的操作:在C盘新建文件file1.txt往里面随意写入一些文字,保存。
运行代码如下:
program CopyOneByteFile; var mychar : string[200]; filein, fileout : text; begin assign (filein, 'c:\file1.txt'); reset (filein); assign (fileout, 'c:\file2.txt'); rewrite (fileout); read (filein, mychar); write (fileout, mychar); close(filein); close(fileout)end.查看C盘中file2.txt的内容。
你是不是知道了,上面是一个操作文件的示例,程序运行在DOS下,将读取file1.txt内容,写入到file2.txt中。
这个过程之中,要是file2.txt不存在,那么它将被创建。
链接:https://www.jianshu.com/p/a1c0172c3408
相关阅读 >>
检查是否在Delphi xe7中启用或禁用了android蓝牙
更多相关阅读请进入《Delphi》频道 >>