Delphi文件操作

 来源:http://www.delphibasics.co.uk/Article.asp?Name=Files

Delphi file support
Delphi provides a number of different file access mechanisms. The oldest is in support of consoles, where the Read, ReadLn, Write and WriteLn routines have a syntax that omits the file name. With no file name, IO (Input and Output) is routed to the console. 
Of greater importance to modern applications, are disk file operations. Disks such as hard disks, floppy disks, CDs and DVDs (the latter are treated as read only). 
Delphi confusingly provides two basic sets of routines for file handling. The most Delphi like are covered by this article and this web site. The other type are thin wrappers around Windows APIs - and as such are platform specific. They also support text files less intuitively. They are not covered here. 
Additionally, hidden away, Delphi provides a very elegant way of reading and writing complete text files. The TStringList class has methods for loading the list of strings from a text file. And for saving the list likewise. See the final section of this article. 

Accessing files
There are a number of basic operations for handling both text and binary files. (The latter can hold non character data values). First, we must get a handle for a named file: 
 var
   myFile : TextFile; 
 begin
   AssignFile(myFile, 'Test.txt');

Here we are getting a handle to a text file, designated by the TextFile type (binary files are of type File). We ask Delphi to assign a file handle for a file called 'Test.txt' which will be assumed to be in the current directory (as given by the GetCurrentDir routine).
 
Next, we must open the file using this handle. This operation tells Delphi how we want to treat the file. There are 3 ways of opening the file:
 
 ReWrite Opens a file as new - discards existing contents if file exists
 Reset   Opens a file for read and write access
 Append  Opens a file for appending to the end (such as a log file)
We'll cover the access mechanisms for text and binary files separately. Meanwhile, when we have finished, we must close the file:
 
   CloseFile(myFile);


Reading and writing to text files
Text files are great for simple uses, such as where we record a processing log. Text files fall short when reading and writing structured data. They do support number to string and string to number formatting, but you are often better off defining your own record structure and using a typed binary file instead.
 
Here is a simple example of access to a text file:
 
 var
   myFile : TextFile;
   text   : string; 
 begin
   // Try to open the Test.txt file for writing to
   AssignFile(myFile, 'Test.txt');
   ReWrite(myFile);
 
   // Write a couple of well known words to this file
   WriteLn(myFile, 'Hello');
   WriteLn(myFile, 'World');
 
   // Close the file
   CloseFile(myFile);
 
   // Reopen the file for reading
   Reset(myFile);
 
   // Display the file contents
   while not Eof(myFile) do
   begin
     ReadLn(myFile, text);
     ShowMessage(text);
   end;
 
   // Close the file for the last time
   CloseFile(myFile);
 end;

 The ShowMessage routine displays the following :
 
 Hello
 World

If we replaced the ReWrite routine with Append, and rerun the code, the existing file would then contain:
 
 Hello
 World
 Hello
 World

since append retains the existing file contents, appending after this anything new written to it.
 
Notice that we have used WriteLn and ReadLn to write to and read from the file. This writes the given text plus a carriage return and line feed to the text. The read reads the whole line up to the carriage return. We have read from the file until Eof (End Of File) is true. See also Eoln.
 
We can use Read and Write to read and write multiple strings to a file. More importantly, we can use these to write numbers as strings, with some useful formatting (see Write for further details):
 
 var
   myFile : TextFile;
   text   : string;
   i      : Integer; 
 begin
   // Try to open the Test.txt file for writing to
   AssignFile(myFile, 'Test.txt');
   ReWrite(myFile);
 
   // Write a couple of well known words to this file
   Write(myFile, 'Hello ');
   Write(myFile, 'World');
 
   // Terminate this line
   WriteLn(myFile);
 
   // Write some numbers to the file as a single line
   for i := 2 to 4 do
     Write(myFile, i/2, '  ');
 
   // Terminate this line
   WriteLn(myFile);
 
   // repeat the above, but with number formatting
   for i := 2 to 4 do
     Write(myFile, i/2:5:1);
 
   // Terminate this line
   WriteLn(myFile);
 
   // Close the file
   CloseFile(myFile);
 
   // Reopen the file for reading only
   Reset(myFile);
 
   // Display the file contents
   while not Eof(myFile) do
   begin
     ReadLn(myFile, text);
     ShowMessage(text);
   end;
 
   // Close the file for the last time
   CloseFile(myFile);
 end;

 Hello World
 1.00000000000000E+0000  1.50000000000000E+0000  2.00000000000000E+0000
 1.0  1.5  2.0


Reading and writing to typed binary files
Typed binary files are files that have a data type as the basic unit of writing and reading. You write, say, an Integer, or a Record to a file, and read the same unit of data back. Records are particularly useful, allowing us to store any mix of data types in the one file unit of data.
 
This is best illustrated with an example:
 
 type
   TCustomer = Record
     name : string[20];
     age  : Integer;
     male : Boolean;
   end;
 
 var
   myFile   : File of TCustomer;  // A file of customer records
   customer : TCustomer;          // A customer record variable 
 begin
   // Try to open the Test.cus binary file for writing to
   AssignFile(myFile, 'Test.cus');
   ReWrite(myFile);
 
   // Write a couple of customer records to the file
   customer.name := 'Fred Bloggs';
   customer.age  := 21;
   customer.male := true;
   Write(myFile, customer);
 
   customer.name := 'Jane Turner';
   customer.age  := 45;
   customer.male := false;
   Write(myFile, customer);
 
   // Close the file
   CloseFile(myFile);
 
   // Reopen the file in read only mode
   FileMode := fmOpenRead;
   Reset(myFile);
 
   // Display the file contents
   while not Eof(myFile) do
   begin
     Read(myFile, customer);
     if customer.male
     then ShowMessage('Man with name '+customer.name+
                      ' is '+IntToStr(customer.age))
     else ShowMessage('Lady with name '+customer.name+
                      ' is '+IntToStr(customer.age));
   end;
 
   // Close the file for the last time
   CloseFile(myFile);
 end;

 Man with name Fred Bloggs is 21
 Lady with name Jane Turner is 45

The code is very similar to that used for text files, except that we define a file of a certain type (record), and pass/receive record data when writing/reading.
 

Reading and writing to pure binary files
Pure binary files are a bit peculiar. You must use BlockRead and BlockWrite instead of Read and Write. These have the added benefit of greater performance than the Read and Write, but are really geared at writing just blocks of binary data.
 
Here is an example :
 
 var
   myFile    : File;
   byteArray : array[1..8] of byte;
   oneByte   : byte;
   i, count  : Integer; 
 begin
   // Try to open the Test.byt file for writing to
   AssignFile(myFile, 'Test.byt');
   ReWrite(myFile, 4);   // Define a single 'record' as 4 bytes
 
   // Fill out the data array
   for i := 1 to 8 do
     byteArray[i] := i;
 
   // Write the data array to the file
   BlockWrite(myFile, byteArray, 2);   // Write 2 'records' of 4 bytes
 
   // Fill out the data array with different data
   for i := 1 to 4 do
     byteArray[i] := i*i;              // Value : 1, 4, 9, 16
 
   // Write only the first 4 items from the data array to the file
   BlockWrite(myFile, byteArray, 1);   // Write 1 record of 4 bytes
 
   // Close the file
   CloseFile(myFile);
 
   // Reopen the file for reading only
   FileMode := fmOpenRead;
   Reset(myFile, 1);   // Now we define one record as 1 byte
 
   // Display the file contents
   // Start with a read of the first 6 bytes. 'count' is set to the
   // actual number read
   ShowMessage('Reading first set of bytes :');
   BlockRead(myFile, byteArray, 6, count);
 
   // Display the byte values read
   for i := 1 to count do
     ShowMessage(IntToStr(byteArray[i]));
 
   // Now read one byte at a time to the end of the file
   ShowMessage('Reading remaining bytes :');
   while not Eof(myFile) do
   begin
     BlockRead(myFile, oneByte, 1);   // Read and display one byte at a time
     ShowMessage(IntToStr(oneByte));
   end;
 
   // Close the file for the last time
   CloseFile(myFile);
 end;

 Reading first set of bytes :
 1
 2
 3
 4
 5
 6
 Reading remaining bytes :
 7
 8
 1
 4
 9
 16


Other file processing mechanisms
Typed binary files provide direct access methods in addition to sequential reads and writes. Click on a routine name to learn more:
 
 FilePos  Gives the file position in a binary or text file
 Seek     Moves to a new position in the file
 SeekEof  Skip to the end of the current line or file
 SeekEoln Skip to the end of the current line or file


Getting information about files and directories
We have only covered data access to files. There are a number of routines that allow you to do all sorts of things with files and directories that contain them:
 
 ChDir           Change the working drive plus path for a specified drive
 CreateDir       Create a directory
 DeleteFile      Delete a file specified by its file name
 Erase           Erase a file
 FileExists      Returns true if the given file exists
 FileSearch      Search for a file in one or more directories
 FileSetDate     Set the last modified date and time of a file
 Flush           Flushes buffered text file data to the file
 GetCurrentDir   Get the current directory (drive plus directory)
 MkDir           Make a directory
 RemoveDir       Remove a directory
 Rename          Rename a file
 RenameFile      Rename a file or directory
 RmDir           Remove a directory
 SelectDirectory Display a dialog to allow user selection of a directory
 SetCurrentDir   Change the current directory
 Truncate        Truncates a file size


Using TStringList to read and write text files
The TStringList class is a very useful utility class that works on a lits of strings, each indexable like an array. The list can be sorted, and supports name/value pair strings, allowing selection by name or value.
 
These lists can be furnished from text files in one fell swoop. Here we show a TStringList object being created, and loaded from a file:
 
 var
   fileData : TStringList;                // Our TStringList variable
 begin
   fileData := TStringList.Create;        // Create the TSTringList object
   fileData.LoadFromFile('Testing.txt');  // Load from Testing.txt file
   ...

We can display the whole file in a Memo box:
 
   memoBox.Text := fileData.Text;

and we can display or process the file with direct access to any line at any time. In the example code below, we open a text file, reverse all lines in the file, and then save it back. Not terribly useful, but it shows the power of TStringList.
 
 var
   fileData : TStringList;
   saveLine : String;
   lines, i : Integer;
 begin
   fileData := TStringList.Create;        // Create the TSTringList object
   fileData.LoadFromFile('Test.txt');     // Load from Testing.txt file
 
   // Reverse the sequence of lines in the file
   lines := fileData.Count;
 
   for i := lines-1 downto (lines div 2) do
   begin
     saveLine := fileData[lines-i-1];
     fileData[lines-i-1] := fileData[i];
     fileData[i] := saveLine;
   end;
 
   // Now display the file
   for i := 0 to lines-1 do
     ShowMessage(fileData[i]);
 
   fileData.SaveToFile('Test.txt');       // Save the reverse sequence file
 end;

Take a look at TStringList to read more. If you are looking for exchange hosting, use the best.

转载于:https://www.cnblogs.com/railgunman/archive/2010/08/16/1801020.html

具有多种最大功率点跟踪(MPPT)方法的光伏发电系统(P&O-增量法-人工神经网络-模糊逻辑控制-粒子群优化)之使用粒子群算法的最大功率点追踪(MPPT)(Simulink仿真实现)内容概要:本文介绍了一个涵盖多个科研领域的综合性MATLAB仿真资源集合,重点聚焦于光伏发电系统中基于粒子群优化(PSO)算法的最大功率点追踪(MPPT)技术的Simulink仿真实现。文档还列举了多种MPPT方法(如P&O、增量电导法、神经网络、模糊逻辑控制等),并展示了该团队在电力系统、智能优化算法、机器学习、路径规划、无人机控制、信号处理等多个方向的技术服务能力与代码实现案例。整体内容以科研仿真为核心,提供大量可复现的Matlab/Simulink模型和优化算法应用实例。; 适合人群:具备一定电力电子、自动控制或新能源背景,熟悉MATLAB/Simulink环境,从事科研或工程仿真的研究生、科研人员及技术人员。; 使用场景及目标:①学习并实现光伏系统中基于粒子群算法的MPPT控制策略;②掌握多种智能优化算法在电力系统与自动化领域的建模与仿真方法;③获取可用于论文复现、项目开发和技术攻关的高质量仿真资源。; 阅读建议:建议结合提供的网盘资料,按照研究方向选取对应模块进行实践,重点关注Simulink模型结构与算法代码逻辑的结合,注重从原理到仿真实现的全过程理解,提升科研建模能力。
热成像人物检测数据集 一、基础信息 数据集名称:热成像人物检测数据集 图片数量: 训练集:424张图片 验证集:121张图片 测试集:61张图片 总计:606张热成像图片 分类类别: - 热成像人物:在热成像图像中的人物实例 - 非热成像人物:在非热成像或普通图像中的人物实例,用于对比分析 标注格式: YOLO格式,包含边界框和类别标签,适用于目标检测任务。数据来源于热成像和视觉图像,覆盖多种场景条件。 二、适用场景 热成像监控与安防系统开发: 数据集支持目标检测任务,帮助构建能够在低光、夜间或恶劣环境下自动检测和定位人物的AI模型,提升监控系统的可靠性和实时响应能力。 红外视觉应用研发: 集成至红外摄像头或热成像设备中,实现实时人物检测功能,应用于安防、军事、救援和工业检测等领域。 学术研究与创新: 支持计算机视觉与热成像技术的交叉研究,助力开发新算法用于人物行为分析或环境适应型检测模型。 教育与培训: 可用于高校或培训机构,作为学习热成像人物检测和AI模型开发的教学资源,提升实践技能。 三、数据集优势 精准标注与多样性: 每张图片均由专业标注员标注,确保边界框定位准确,类别分类清晰。包含热成像和非热成像类别,提供对比数据,增强模型的泛化能力和鲁棒性。 场景实用性强: 数据覆盖多种环境条件,如不同光照和天气,模拟真实世界应用,适用于复杂场景下的人物检测任务。 任务适配性高: YOLO标注格式兼容主流深度学习框架(如YOLOv5、YOLOv8等),可直接加载使用,支持快速模型开发和评估。 应用价值突出: 专注于热成像人物检测,在安防、监控和特殊环境检测中具有重要价值,支持早期预警和高效决策。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值