我想知道pascal的几个函数(10分)

  • 主题发起人 主题发起人 完颜康
  • 开始时间 开始时间

完颜康

Unregistered / Unconfirmed
GUEST, unregistred user!
就象C里面的
FILE *pt
pt=fopen('c://test.txt','W+')
fclose(pt);
用pascal怎么建立/打开一个原有的文件,以及在这个文件中查找固定的文字
以及相关的函数
 
assginfile

look the Help!
 
要是没有help look怎么办
 
如果是文本文件,你可以
f:textfile
用到几个函数
assignfle
rset
read
write
closefile

如果是记录的你可以
f:file
fileopen
fileseek
fileread
filewrite
fileclose

不过个人比较喜欢用文件流的方法,
f:tfilestream
f:=tfilestream.create
f.loadfromfile
f.readbuffer
f.writebuffer
f.seek
f.free

希望对你有帮助。
 
查找可以用pos()
 
function FileOpen(const FileName: string
Mode: LongWord): Integer;

Mode constants:
const fmOpenRead = $0000;
const fmOpenWrite = $0001;
const fmOpenReadWrite = $0002;
const fmShareCompat = $0000;
const fmShareExclusive = $0010;
const fmShareDenyWrite = $0020;
const fmShareDenyRead = $0030;
const fmShareDenyNone = $0040;
 
我给你一份完整的函数表,发给你,
 
函数表,给我一份好吗!
njpf@elong.com
 
清风老兄:
可以给我一份嘛?
我的Email:q.s.p.2000@263.net
 
to:清风
老兄~我怎么没有收到~
 
俺的email:
yj5637899@21cn.com
 
给我一份啊!njpf@elong.com
 
清风老哥,也发一份给我好吗?
我的EMAIL :pipghost@8848.net
 
Delphi的Help白做了,你们会学习吗?
 
清风大虾,我是一名初学者,能给我一份函数表吗??
多谢了!!
我的信箱是: yiyiqd@163.com
 
老文章,但是对文件操作讲的很好,大家可以参考一下
Using Text Files With Delphi 1
by Glenn Lawrence
Presented to Australian Delphi User Group - July 1996

Synopsis:
This document was presented by the author at the July 1996 meeting of the
Australian Delphi User Group in Melbourne. It examines the generic Pascal-style
file I/O features of Delphi. Particularly as they pertain to the reading and
writing of text files.

Disclaimer:
This document was written when I was a newcomer to Delphi. Even though I have
revisited the document since originally writing it in July 1996 be aware that
it may well contain inaccuracies. The author does not accept liability arising
from use or misuse of the information in this document.

Acknowledgement:
Thanks to those members of the ADUG who gave me useful feedback on this document
and helped me to find and remove a few of the more glaring errors of content.
Any remaining errors are entirely my responsibility - but I still don't want
you to sue me! J

Background:
Apart from college projects in Pascal, prior to writing this document most of
my programming experience was in C and C++. I found that although Windows API
functions were much the same, the generic text file I/O API is quite different
between Delphi and C.

The version of Delphi I was using was Delphi 1 and I found that this did not
support the file handling part of the Windows API very well. In particular
there were real problems with conversion of C-style strings into Pascal strings,
particularly for long strings.

I decided therefore that I would have to learn Delphi's generic Pascal-style
file handling API (AssignFile, Reset, Rewrite etc) to allow me to fulfil a
requirement I had for reading and writing strings to a text file.

This document is the result of my limited research into that API and was written
primarily for my own reference. Hopefully you will find it useful as well.

Please note that if you are programming in the later versions of Delphi that
support conversion between C and Pascal style strings you should probably use
the Windows API as it supports multi-tasking concepts such as file sharing and
locking much more readily.

Pascal-style file I/O:
Delphi's underlying language is Object Pascal. This is Borland's own language
that was in the distant past derived from the original Pascal by Nick Wirth.
Object Pascal has a generic file I/O API that in the old days was also intended
to be used for DOS as well as Windows. It is loosely based on the original Pascal I/O.

Object-Pascal recognises three basic file types:
· Typed
· Untyped
· Text

As I understand it the Typed variety basically allows for a file which is a sequence
of homogeneous basic Pascal objects, including the various scalar types plus records,
but not true “object types”. It was useful for teaching about random file access,
but the file format is non-standard and non-portable. Streams would probably be
a better way to go, assuming you can figure them out that is.

I have never used the Untyped variety that I can recall. It seems to be for low
level, almost physical layer, I/O. It might be useful for general binary file
I/O but I doubt it. If you do feel tempted to use this file type don’t forget
about issues of portability. Can a program written in another language or on
another platform read it?

In the original Pascal Text files were just a particular sort of Typed file,
a "file of char". Object Pascal however distinguishes between these types and
their semantics are different.

Text files have the advantage of being compatible with standard ASCII text files
which are produced by editors and other programs on Windows and on other platforms.
They therefore enjoy the great advantage of portability. They also allow for
visibility, which makes debugging easier, but this can also be a problem if you
want to keep the content of your files from prying eyes and fingers.

I also believe that it is easier to manage several different file format versions
with text files.

Pascal text files do however have some disadvantages, which are listed below:
· No support for random file access.
· Visibility allows file content to be seen and edited by others.
· File name and line length problems - see the later Gotchas section.
· Support for Windows specific features such as controlled file sharing is poor.

Given these disadvantages you may wish to also consider other options set in the next section.
Other options
The Windows API (see “File I/O Functions (3.1)” below) offers various file I/O facilities.
It tends to be more complicated than the Pascal stuff, but you can do more things
like file sharing and locking. It also requires you to work with Pchar type strings,
which can be a bit of a pain when everything else uses Pascal strings. (NB: This is
not such a big problem in the 32bit versions of Delphi)

There are also a number of Windows API functions the names of which start with either
WritePrivateProfile or GetPrivateProfile that you can put to use for reading and
writing text files. I haven’t tried them for anything other than standard .INI
file format, but I understand they will work more generally.

If you just want to be able to load and save a small table of strings you could
consider creating a TStringList object and using its LoadFromFile and SaveToFile
methods.

Delphi has a poorly documented “streams” feature as expressed in objects like
TStream, TFileStream, TReader, TWriter and TPersistent. It reminds me of the
Visual C++ “serialise” feature in that it seems to allow the saving of true
objects to “streams” which can be binary files. It looks really useful, but I
can find no reference to it in the paper docs or any of my text books, and very
little in the on-line help. If you want to use this feature it looks like you’ll
have to UTSL (assuming you have a source licence of course!). If there is enough
interest I might try to research this a bit more and do another presentation later.

Finally there is a very useful set of routines in the LZExpand unit that support
things like file copying and compression. Look up LZExpand in the Windows API help.

The Delphi file I/O API
The following information was largely lifted from the Delphi 1.0 help file. Later versions may differ.

Please note that many of the "routines" listed below are not strictly Pascal functions and procedures.
They are actually built into the Object Pascal language. This means that they
don't have to follow the same strict syntax rules that normal routines are
subject to, especially with regard to type checking. The Read and Write "routines"
are particularly anomolous in this regard.

In the following sections I have underlined those "routines" which are compatible
with Pascal-style text files and my comments are italicised. I have also emboldened
those that I believe to be most important.

General I/O Routines

AssignFile Assigns the name of an external file to a file variable.
CloseFile Closes an open file.
Eof Returns the end-of-file status. (True implies at end of file)
Erase Erases an external file.
FilePos Returns the current file position of a file.
FileSize Returns the current size of a file.
GetDir Returns the current directory of specified drive.
IOResult Returns the status of the last I/O operation performed (but only if you aren’t using exceptions for this - see later section on Error Handling)
MkDir Creates a subdirectory (beware length limits - see later Gotchas section)
Rename Renames an external file.
Reset Opens an existing file (for reading)
Rewrite Creates and opens a new file (or opens and clears an existing file!)
RmDir Removes an empty subdirectory.
Seek Moves the current position of a file to a specified component.
Truncate Truncates the file at the current file position.

The routines FilePos, FileSize and Seek do not work for text files (even though the
syntax allows their use!)

The I/O routines section of the help file omits another useful routine
which is ChDir which allows you to set the current working directory.
You can get information on it by using the help search facility.

Text-file Routines

Append Opens an existing file for appending.
Eoln Returns the end-of-line status of a text file.
Flush Flushes the buffer of a text file open for output.
Read For typed files, reads a file component into a variable. For text files, reads one or more values into one or more variables
Readln Executes the Read procedure, then skips to the next line of the file.
SeekEof Returns the end-of-file status of a file.
SeekEoln Returns the end-of-line status of a file.
SetTextBuf Assigns an I/O buffer to a text file..
Write For typed files, writes a variable into a file component. For text files, writes one or more values to the file
Writeln Executes the Write procedure, then outputs an end-of-line marker to the file.

Most of these routines are relevant but I have emboldened only those that seem
most important to me.

All these routines are in the System unit (but you don’t need to explicitly
declare it)

Untyped-file Routines

BlockRead Reads one or more records into a variable.
BlockWrite Writes one or more records from a variable.

Since I am dealing with only text files, these routines are not really relevant. They are mentioned here for completeness only.

File-management Routines
ChangeFileExt Changes the file extension
DateTimeToFileDate Converts the Delphi date format to the DOS date format.
DeleteFile Removes a file.
DirectoryExists Returns True if directory exists. See note below
DiskFree Returns the amount of free disk space.
DiskSize Returns the size of the specified disk.
ExpandFileName Returns a string containing a fully qualified path name and file name
ExtractFileExt Returns only the file extension.
ExtractFileName Returns only the file name.
ExtractFilePath Returns the path to the specified file.
FileAge Returns the age of a file
FileCreate Creates a file with the specified name.
*FileClose Closes the specified file
FileDateToDateTime Converts a DOS date format to the Delphi date format.
FileExists Returns True if file exists.
FileGetAttr Returns file attributes
*FileGetDate Returns the DOS date-and-time stamp of the file.
*FileRead Reads from a specific file.
FileSearch Searches through the directories for a specific file.
*FileSeek Changes the current position of the file.
FileSetAttr Sets file attributes
*FileSetDate Sets the DOS date-and-time stamp of the file.
*FileOpen Opens a specific file.
*FileWrite Writes to a specific file.
FindClose Terminates a FindFirst/FindNext sequence.
FindFirst Searches a directory for a specified file name and set of attributes.
FindNext Returns the next entry that matches the name and attributes.
RenameFile Renames a file.

Most of these routines take path names to identify the file, but those marked with
and asterisk (*) take or return an integer value which is known as a “file handle”.
It is possible to get to the file handle of an opened Pascal-style file by casting
the TextFile into a TTextRec - see TTextRec in the on-line help. The documentation
isn't very helpful, basically saying don't use it unless you already know about it
- thanks Borland! It's probably safe to use the date manipulation routines, but I would be reluctant to use the other routines on TextFile types without really understanding the underlying how the Pascal-style API has actually been implemented.

Warning: In early versions of the on-line help FileOpen and FileWrite are incorrectly
designated as "internal functions". This was fixed in later versions.

With the exception of DirectoryExists these routines are in the SysUtils unit
so include it in your Uses clause to access them.

DirectoryExists is a special case as it actually lives in the FileCtrl unit,
which is primarily concerned with the file open dialog box - see FileCtrl in
the on-line help. Warning: DirectoryExists doesn't work for root directories
like 'C:/'.

Windows File I/O Functions (3.1)

GetDriveType Determines the drive type
GetSystemDirectory Returns the path of the Windows system directory
GetTempDrive Returns a disk drive letter for temporary files
GetTempFileName Creates a temporary filename
GetWindowsDirectory Returns the path of the Windows directory
_hread Reads data from a file
_hwrite Writes data to a file
_lclose Closes an open file
_lcreat Creates or opens a file
_llseek Repositions the file pointer
_lopen Opens an existing file
_lread Reads data from a file
_lwrite Writes data to a file
hmemcpy Copies bytes from source to destination buffer (Shouldn’t be in this section!)
OpenFile Creates, opens, reopens, or deletes a file
SetHandleCount Changes the number of available file handles

Those starting with underscore_ are the low-level routines for accessing files through
Windows. They all require a file handle. As mentioned in the previous section you
can get a file handle by casting the TextFile to a TTextRec, but I wouldn't really
recommend mixing these routines with the standard Pascal-style stuff.

I haven’t used the SetHandleCount API in Delphi, but I suspect that Delphi apps
are also limited to a default maximum of 20 files open at one time. You can use
this routine to increase that limit. It probably should have been called something
like SetMaxTaskFileHandles.

The hmemcpy routine has nothing whatsoever to do with file I/O, it’s appearance
in this section is a mistake that has since been rectified in later help files.


Examples
The following examples show how to save and load a TMemo from file "the hard way".
You could of course use the SaveToFile and LoadFromFile methods of TStrings,
but then you wouldn't learn about text file I/O!

{ BadSaveMemoToFile:
This procedure saves the contents of a TMemo to a given file.
No file I/O errors are caught.

Warning: This procedure contains a deliberate fault.
}
procedure BadSaveMemoToFile(Memo : TMemo
FileName : string);
var
OutFile : TextFile
{ The text file }
Counter : integer
{ Loop counter }
begin
AssignFile(OutFile, FileName)
{ Associate OutFile with name }
Rewrite(OutFile)
{ Open it }

for Counter := 0 to Memo.Lines.Count - 1 do
Writeln(OutFile, Memo.Lines[Counter]);

CloseFile(OutFile);
end;

The above example demonstrates the basic concepts and shows how to open a text file
and write to it.

There is a deliberate mistake in that if file I/O errors are detected with exceptions
and a file I/O error occurs the file will not be closed.


{ SimpleSaveMemoToFile:
This procedure saves the contents of a TMemo to a given file.
No file I/O errors are caught.
}
procedure SimpleSaveMemoToFile(Memo : TMemo
FileName : string);
var
OutFile : TextFile
{ The text file }
Counter : integer
{ Loop counter }

begin

AssignFile(OutFile, FileName)
{ Associate OutFile with name }
Rewrite(OutFile)
{ Open it }

try
for Counter := 0 to Memo.Lines.Count - 1 do
Writeln(OutFile, Memo.Lines[Counter]);

finally
CloseFile(OutFile);
end

end;

This example rectifies the fault in the preceding example by enclosing the file
access code in a try-finally block. This ensures that OutFile will always be
closed even if an exception is raised while writing the file.

{ SaveMemoToFile:
This procedure saves the contents of a TMemo to a given file.
File I/O errors are caught and processed.
}
procedure SaveMemoToFile(Memo : TMemo
FileName : string);
var
OutFile : TextFile
{ The text file }
Counter : integer
{ Loop counter }
begin
AssignFile(OutFile, FileName)
{ Associate OutFile with name }
Rewrite(OutFile)
{ Open it }
try
try
for Counter := 0 to Memo.Lines.Count - 1 do
Writeln(OutFile, Memo.Lines[Counter]);
except on E:EInOutError do
MessageDlg('Save aborted with error: ' + IntToStr(E.ErrorCode)
, mtError, [mbOK], 0);
end;
finally
CloseFile(OutFile);
end;
end;

The above example shows how to catch a file I/O exception and extract the error code from it. Note that it is good form to keep the outer try-finally block in case a non I/O exception is raised.

{ SimpleLoadMemoFromFile:
This procedure loads the contents of a TMemo from a given file.
No file I/O errors are caught.
}
procedure SimpleLoadMemoFromFile(Memo : TMemo
FileName : string);
var
InFile : TextFile
{ The text file }
Line : string
{ The line read in }

begin
Memo.Lines.Clear
{ Empty the memo }

AssignFile(InFile, FileName)
{ Associate InFile with file name }
Reset(InFile)
{ Open it without clobbering it }
try
while not Eof(InFile) do
begin
Readln(InFile, Line);
Memo.Lines.Add(Line);
end;
finally
CloseFile(InFile);
end

end;

Finally this example shows how reverse the process of reading text from a file.
Note that Readln copies all text up to but not including the end of line marker
into the given string. It then skips past the end of line marker to the next line
if there is one. If there is no next line then EOF becomes True.

Although these examples don't show it, be aware that you can also read and write
non-string types to text files. There are even some simple formatting features.
Look up "Read procedure" and "Write procedure" in the on line help for more information.
Printing with Text File I/O
An advantage of Object Pascal text files that I haven’t yet mentioned is that
they can be used to send data directly to devices. This example shows how you
can send text directly to the printer.

{ PrintMemo:
This procedure prints the contents of a TMemo.
}
procedure PrintMemo(Memo : TMemo
FileName : string);
var
OutFile : TextFile
{ The text file }
Counter : integer
{ Loop counter }
begin
AssignPrn(OutFile)
{ Assign text file to PRN }
Rewrite(OutFile)
{ Open it }
try
for Counter := 0 to Memo.Lines.Count - 1 do
Writeln(OutFile, Memo.Lines[Counter]);
finally
CloseFile(OutFile);
end;
end;

Note that in this case I am using AssignPrn rather than AssignFile. Having done
this you can simply write to the printer as if it was a "normal" text file. You
can modify printer attributes by accessing the global Printer object - see the
onl-line help. I have found however that to ensure that changes take effect you
need to do them after you call AssignPrn. NB: AssignPrn and Printer are defined
in the Printers unit and you will need to include it in your uses clause.

Apparently it is also possible to define your own text file drivers for other
devices than just the printer, although I haven’t tried it. For more info you
could start by looking for AssignDev in the on-line help.

Error handling
In the foregoing examples I have shown some basic error handling using Delphi
exceptions.There is a lot more that can be said about Delphi exceptions, but
maybe that can be left to future presentation. If you are interested there is
plenty of information in the on-line help and the “Object Pascal Language
Guide” that comes with Delphi.If you don’t want to use exceptions there is
an alternative error handling mechanism which involves calling the IOResult
function (see “I/O Routines” above) and checking the returned value after
doing any File I/O. I haven’t used this method as exceptions seem much simpler
and more natural to me.To use IOResult then you will have to switch off the
$I compiler flag. You can do this for the whole project by going into
Options->Project->Compiler and un-checking the I/O Checking check box. A better
idea would be to leave the check box checked and switch the compiler flag in your
code using {$I-} and {$I+} around those areas where you want to use the older
method of error handling.Note: if you switch off exception mode error handling
using {$I-} you have to clear any errors by calling IOResult before returning
to the exception mode of error handling. Unfortunately IOResult is a special
function that insists on returning a value so you can't just call it to clear
it. Here is an example of how to do this:

class function GLU.CloseFileSansException(var f: TextFile) : integer;
begin
{$I-}
CloseFile(f);
Result := IOResult;
{$I+}
end;
Gotchas
File name problems
AssignFile does not check the file name for syntax errors, you only find out
about it when you try to Open the file.

AssignFile will accept an empty string as a file name but when you Open this
file it will assume it to be the "console". This makes sense for DOS programs,
but causes grief for Windows programs as output to this file will cause rubbish to appear on the screen.

The on-line help says that that AssignFile can only accept a file name of up to
80 characters. In fact it is worse than this since the underlying DOS file system
can only handle paths up to 63 characters (excluding drive name) in length. You
can’t work around this problem by using ChDir since the limit applies to the
full path, not just the relative path that you might be using.

Other file management routines including MkDir are also affected by this limit,
but how you could create and access files in a directory at this limit I don't
know. To make things worse MkDir (and probably other routines) doesn't check
the length of the string you give, it just quietly truncates it without raising
an exception. This is a particularly nasty gotcha to look out for.

The API docs say that AssignFile can only accept a file name with a simple letter
drive designation. The implication is that unlike the Windows API routines it doesn’t
support Lan Manager style UNC qualifiers. I haven’t tried this to see if it’s
the case. If you need to access files on another PC on the network you will probably
first have to map a "network drive" to a local drive letter.
Line length limits
Delphi's old Pascal style strings only allow a maximum length of 255 characters.
This is a problem if you want to read long lines into strings. Even using Read
rather than Readln won't help because it still reads the whole line in for string
types. It is possible to write long lines using a number of Write calls, but this
isn’t much use if you can't read them back in again.
Synonyms
To retain compatibility with old Pascal there are some identifiers which are synonyms.
In particular:

Old name New name
Text TextFile
Assign AssignFile
Close CloseFile

The names were changed to prevent collisions with things like TForm.Close.
It is possible to also avoid collisions by qualifying the names with System
(eg: System.Close) and you will see this in many places in the on-line documentation.
I would recommend in the interests of readability to use the new names in preference

to the old.
 
hehe,呵呵,还有一件事要对你说说。
pascal是不管大小写的,你怎么写都一样,不像C
 
多人接受答案了。
 
后退
顶部