Free Pascal supplied units : Reference guide. Reference guide for standard Free Pascal units. 1.6 July 1999 Micha¨el Van Canneyt Florian Kl¨ampfl Contents 1 The CRT unit. 21 1.1 Types, Variables, Constants . . . . . . . . . . . . . . . . . . . . . . . 21 1.2 Procedures and Functions . . . . . . . . . . . . . . . . . . . . . . . . 22 AssignCrt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22 BigCursor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 ClrEol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 ClrScr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24 CursorO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24 CursorOn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24 Delay . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24 DelLine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25 GotoXY . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25 HighVideo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26 InsLine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26 KeyPressed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27 LowVideo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27 NormVideo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28 NoSound . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28 ReadKey . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28 Sound . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29 TextBackground . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29 TextColor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30 WhereX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30 WhereY . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31 Window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31 2 The DOS unit. 33 2.1 Types, Variables, Constants . . . . . . . . . . . . . . . . . . . . . . . 33 Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33 Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35 1 CONTENTS 2.2 Functions and Procedures . . . . . . . . . . . . . . . . . . . . . . . . 36 AddDisk . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36 DiskFree . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36 DiskSize . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37 DosExitCode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37 DosVersion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38 EnvCount . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38 EnvStr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39 Exec . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39 FExpand . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39 FindClose . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40 FindFirst . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40 FindNext . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41 FSearch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41 FSplit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42 GetCBreak . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42 GetDate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42 GetEnv . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43 GetFAttr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43 GetFTime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44 GetIntVec . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45 GetTime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45 GetVerify . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46 Intr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46 Keep . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46 MSDos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46 PackTime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47 SetCBreak . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47 SetDate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48 SetFAttr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48 SetFTime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48 SetIntVec . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48 SetTime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49 SetVerify . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49 SwapVectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49 UnPackTime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49 3 The GETOPTS unit. 50 3.1 Types, Constants and variables : . . . . . . . . . . . . . . . . . . . . 50 Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50 2 CONTENTS Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51 3.2 Procedures and functions . . . . . . . . . . . . . . . . . . . . . . . . 51 GetLongOpts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51 Getopt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51 4 The GO32 unit 54 4.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54 4.2 Protected mode memory organization . . . . . . . . . . . . . . . . . 54 What is DPMI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54 Selectors and descriptors . . . . . . . . . . . . . . . . . . . . . . . . . 54 FPC specialities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55 dos memory access . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55 I/O port access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55 Processor access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55 Interrupt redirection . . . . . . . . . . . . . . . . . . . . . . . . . . . 56 Handling interrupts with DPMI . . . . . . . . . . . . . . . . . . . . . 56 Protected mode interrupts vs. Real mode interrupts . . . . . . . . . 56 Creating own interrupt handlers . . . . . . . . . . . . . . . . . . . . 56 Disabling interrupts . . . . . . . . . . . . . . . . . . . . . . . . . . . 56 Hardware interrupts . . . . . . . . . . . . . . . . . . . . . . . . . . . 56 Software interrupts . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58 Real mode callbacks . . . . . . . . . . . . . . . . . . . . . . . . . . . 61 4.3 Types, Variables and Constants . . . . . . . . . . . . . . . . . . . . . 62 Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62 Predefined types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62 Variables. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64 4.4 Functions and Procedures . . . . . . . . . . . . . . . . . . . . . . . . 64 allocate ldt descriptors . . . . . . . . . . . . . . . . . . . . . . . . . 64 allocate memory block . . . . . . . . . . . . . . . . . . . . . . . . . 66 copyfromdos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66 copytodos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67 create code segment alias descriptor . . . . . . . . . . . . . . . . 67 disable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67 dosmemfillchar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68 dosmemfillword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69 dosmemget . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69 dosmemmove . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69 dosmemput . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70 enable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70 3 CONTENTS free ldt descriptor . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70 free memory block . . . . . . . . . . . . . . . . . . . . . . . . . . . 71 free rm callback . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71 get cs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71 get descriptor access rights . . . . . . . . . . . . . . . . . . . . . . 71 get ds . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72 get linear addr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72 get meminfo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72 get next selector increment value . . . . . . . . . . . . . . . . . . 73 get page size . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74 get pm interrupt . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74 get rm callback . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74 get rm interrupt . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77 get run mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78 get segment base address . . . . . . . . . . . . . . . . . . . . . . . 78 get segment limit . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79 get ss . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79 global dos alloc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79 global dos free . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81 inportb . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81 inportl . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81 inportw . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81 lock code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82 lock data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82 lock linear region . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82 outportb . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83 outportl . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83 outportw . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83 realintr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84 seg fillchar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84 seg fillword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85 segment to descriptor . . . . . . . . . . . . . . . . . . . . . . . . . 85 seg move . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86 set descriptor access rights . . . . . . . . . . . . . . . . . . . . . . 86 set pm interrupt . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86 set rm interrupt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88 set segment base address . . . . . . . . . . . . . . . . . . . . . . . 88 set segment limit . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88 tb size . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89 transfer bu er . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89 4 CONTENTS unlock code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89 unlock data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89 unlock linear region . . . . . . . . . . . . . . . . . . . . . . . . . . . 90 5 The GRAPH unit. 91 5.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91 Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91 5.2 Constants, Types and Variables . . . . . . . . . . . . . . . . . . . . . 91 Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91 5.3 Functions and procedures . . . . . . . . . . . . . . . . . . . . . . . . 92 Arc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92 Bar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92 Bar3D . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92 Circle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92 ClearDevice . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93 ClearViewPort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93 CloseGraph . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93 DetectGraph . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93 DrawPoly . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93 Ellipse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94 FillEllipse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94 FillPoly . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94 FloodFill . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94 GetArcCoords . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94 GetAspectRatio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95 GetBkColor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95 GetColor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95 GetDefaultPalette . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95 GetDriverName . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95 GetFillPattern . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95 GetFillSettings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96 GetGraphMode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96 GetImage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96 GetLineSettings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96 GetMaxColor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96 GetMaxMode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96 GetMaxX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97 GetMaxY . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97 GetModeName . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97 GetModeRange . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97 5 CONTENTS GetPalette . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97 GetPaletteSize . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97 GetPixel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98 GetTextSettings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98 GetViewSettings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98 GetX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98 GetY . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98 GraphDefaults . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99 GraphErrorMsg . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99 GraphResult . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99 ImageSize . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99 InitGraph . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100 InstallUserDriver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100 InstallUserFont . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100 Line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101 LineRel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101 LineTo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101 MoveRel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101 MoveTo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101 OutText . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102 OutTextXY . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102 PieSlice . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102 PutImage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102 PutPixel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102 Rectangle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103 RegisterBGIDriver . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103 RegisterBGIFont . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103 RestoreCRTMode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103 Sector . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103 SetActivePage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104 SetAllPallette . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104 SetAspectRatio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104 SetBkColor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104 SetColor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104 SetFillPattern . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105 SetFillStyle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105 SetGraphBufSize . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105 SetGraphMode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105 SetLineStyle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106 SetPalette . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106 6 CONTENTS SetRGBPalette . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106 SetTextJustify . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106 SetTextStyle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107 SetUserCharSize . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107 SetViewPort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107 SetVisualPage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108 SetWriteMode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108 TextHeight . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108 TextWidth . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108 6 The HEAPTRC unit. 109 6.1 Purpose . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109 6.2 Usage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109 6.3 Constants, Types and variables . . . . . . . . . . . . . . . . . . . . . 111 6.4 Functions and procedures . . . . . . . . . . . . . . . . . . . . . . . . 111 DumpHeap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111 MarkHeap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111 SetExtraInfo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112 7 The IPC unit. 114 7.1 Types, Constants and variables : . . . . . . . . . . . . . . . . . . . . 114 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114 Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114 Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115 7.2 Functions and procedures . . . . . . . . . . . . . . . . . . . . . . . . 119 ftok . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119 msgget . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119 msgsnd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119 msgrcv . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120 msgctl . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120 semget . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123 semop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123 semctl . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124 shmget . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129 shmat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129 shmdt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130 shmctl . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130 8 The LINUX unit. 133 8.1 Type, Variable and Constant declarations . . . . . . . . . . . . . . . 133 Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133 7 CONTENTS Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136 Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136 8.2 Functions and procedures . . . . . . . . . . . . . . . . . . . . . . . . 139 Access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139 AssignPipe . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140 AssignStream . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141 BaseName . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142 CFMakeRaw . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143 CFSetISpeed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143 CFSetOSpeed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143 Chown . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143 Chmod . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144 CloseDir . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146 DirName . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146 Dup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146 Dup2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147 EpochToLocal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148 Execl . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148 Execle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149 Execlp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150 Execv . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150 Execve . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151 Execvp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152 FD ZERO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153 FD Clr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153 FD IsSet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153 FD Set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154 fdClose . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154 fdFlush . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154 fdOpen . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154 fdRead . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155 fdSeek . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156 fdTruncate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156 fdWrite . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157 FExpand . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157 FLock . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157 FSStat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158 FSearch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159 FStat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159 Fcntl . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160 8 CONTENTS Fcntl . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160 Fork . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161 GetDate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161 GetDomainName . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162 GetEGid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162 GetEUid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163 GetEnv . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163 GetEpochTime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163 GetFS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164 GetGid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164 GetHostName . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165 GetPid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165 GetPPid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166 GetPriority . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166 GetTime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166 GetUid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167 Glob . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167 GlobFree . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168 IOCtl . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168 IOperm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169 IsATTY . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169 S ISBLK . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169 S ISCHR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169 S ISDIR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170 S ISFIFO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170 S ISLNK . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170 S ISREG . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171 S ISSOCK . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171 Kill . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171 LStat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172 Link . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173 LocalToEpoch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174 MkFifo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175 Nice . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175 OpenDir . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176 PClose . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177 POpen . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177 ReadDir . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178 SeekDir . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178 Select . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178 9 CONTENTS SelectText . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180 SetPriority . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180 Shell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180 SigAction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181 SigPending . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182 SigProcMask . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182 SigSuspend . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183 Signal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183 SymLink . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184 TCDrain . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185 TCFlow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185 TCFlush . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185 TCGetAttr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186 TCGetPGrp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186 TCSendBreak . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187 TCSetAttr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187 TCSetPGrp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187 TTYName . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187 TellDir . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188 Umask . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188 Uname . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188 UnLink . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188 Utime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189 WaitPid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190 9 The MMX unit 191 9.1 Variables, Types and constants . . . . . . . . . . . . . . . . . . . . . 191 9.2 Functions and Procedures . . . . . . . . . . . . . . . . . . . . . . . . 192 Emms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192 10 The Mouse unit 193 10.1 Constants, types and variables . . . . . . . . . . . . . . . . . . . . . 193 10.2 Functions and procedures . . . . . . . . . . . . . . . . . . . . . . . . 194 GetLastButtonPress . . . . . . . . . . . . . . . . . . . . . . . . . . . 194 GetLastButtonRelease . . . . . . . . . . . . . . . . . . . . . . . . . . 195 GetMouseState . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196 HideMouse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197 InitMouse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197 LPressed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198 MPressed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198 RPressed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198 10 CONTENTS SetMouseAscii . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198 SetMouseHideWindow . . . . . . . . . . . . . . . . . . . . . . . . . . 199 SetMousePos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200 SetMouseShape . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200 SetMouseSpeed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201 SetMouseWindow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202 SetMouseXRange . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202 SetMouseYRange . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203 ShowMouse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203 11 The Objects unit. 204 11.1 Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204 11.2 Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205 11.3 Procedures and Functions . . . . . . . . . . . . . . . . . . . . . . . . 206 NewStr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206 DisposeStr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207 Abstract . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207 RegisterObjects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207 RegisterType . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207 LongMul . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209 LongDiv . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209 11.4 TRect . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209 TRect.Empty . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210 TRect.Equals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211 TRect.Contains . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211 TRect.Copy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211 TRect.Union . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212 TRect.Intersect . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212 TRect.Move . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213 TRect.Grow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214 TRect.Assign . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214 11.5 TObject . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214 TObject.Init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215 TObject.Free . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215 TObject.Done . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215 11.6 TStream . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 216 TStream.Get . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217 TStream.StrRead . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217 TStream.GetPos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218 TStream.GetSize . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219 11 CONTENTS TStream.ReadStr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219 TStream.Open . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220 TStream.Close . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220 TStream.Reset . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220 TStream.Flush . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220 TStream.Truncate . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221 TStream.Put . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221 TStream.StrWrite . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221 TStream.WriteStr . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221 TStream.Seek . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222 TStream.Error . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222 TStream.Read . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222 TStream.Write . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223 TStream.CopyFrom . . . . . . . . . . . . . . . . . . . . . . . . . . . 223 11.7 TDosStream . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224 TDosStream.Init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224 TDosStream.Done . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225 TDosStream.Close . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225 TDosStream.Truncate . . . . . . . . . . . . . . . . . . . . . . . . . . 225 TDosStream.Seek . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226 TDosStream.Open . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227 TDosStream.Read . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227 TDosStream.Write . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228 11.8 TBufStream . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228 TBufStream.Init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229 TBufStream.Done . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229 TBufStream.Close . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229 TBufStream.Flush . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230 TBufStream.Truncate . . . . . . . . . . . . . . . . . . . . . . . . . . 230 TBufStream.Seek . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231 TBufStream.Open . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231 TBufStream.Read . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231 TBufStream.Write . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231 11.9 TMemoryStream . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232 TMemoryStream.Init . . . . . . . . . . . . . . . . . . . . . . . . . . . 232 TMemoryStream.Done . . . . . . . . . . . . . . . . . . . . . . . . . . 232 TMemoryStream.Truncate . . . . . . . . . . . . . . . . . . . . . . . . 233 TMemoryStream.Read . . . . . . . . . . . . . . . . . . . . . . . . . . 233 TMemoryStream.Write . . . . . . . . . . . . . . . . . . . . . . . . . . 234 11.10TCollection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234 12 CONTENTS TCollection.Init . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235 TCollection.Load . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235 TCollection.Done . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236 TCollection.At . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236 TCollection.IndexOf . . . . . . . . . . . . . . . . . . . . . . . . . . . 237 TCollection.GetItem . . . . . . . . . . . . . . . . . . . . . . . . . . . 238 TCollection.LastThat . . . . . . . . . . . . . . . . . . . . . . . . . . 238 TCollection.FirstThat . . . . . . . . . . . . . . . . . . . . . . . . . . 239 TCollection.Pack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239 TCollection.FreeAll . . . . . . . . . . . . . . . . . . . . . . . . . . . . 240 TCollection.DeleteAll . . . . . . . . . . . . . . . . . . . . . . . . . . 241 TCollection.Free . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242 TCollection.Insert . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243 TCollection.Delete . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243 TCollection.AtFree . . . . . . . . . . . . . . . . . . . . . . . . . . . . 244 TCollection.FreeItem . . . . . . . . . . . . . . . . . . . . . . . . . . . 244 TCollection.AtDelete . . . . . . . . . . . . . . . . . . . . . . . . . . . 245 TCollection.ForEach . . . . . . . . . . . . . . . . . . . . . . . . . . . 245 TCollection.SetLimit . . . . . . . . . . . . . . . . . . . . . . . . . . . 246 TCollection.Error . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 246 TCollection.AtPut . . . . . . . . . . . . . . . . . . . . . . . . . . . . 247 TCollection.AtInsert . . . . . . . . . . . . . . . . . . . . . . . . . . . 247 TCollection.Store . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 248 TCollection.PutItem . . . . . . . . . . . . . . . . . . . . . . . . . . . 248 11.11TSortedCollection . . . . . . . . . . . . . . . . . . . . . . . . . . . . 248 TSortedCollection.Init . . . . . . . . . . . . . . . . . . . . . . . . . . 249 TSortedCollection.Load . . . . . . . . . . . . . . . . . . . . . . . . . 250 TSortedCollection.KeyOf . . . . . . . . . . . . . . . . . . . . . . . . 250 TSortedCollection.IndexOf . . . . . . . . . . . . . . . . . . . . . . . . 250 TSortedCollection.Compare . . . . . . . . . . . . . . . . . . . . . . . 250 TSortedCollection.Search . . . . . . . . . . . . . . . . . . . . . . . . 251 TSortedCollection.Insert . . . . . . . . . . . . . . . . . . . . . . . . . 252 TSortedCollection.Store . . . . . . . . . . . . . . . . . . . . . . . . . 253 11.12TStringCollection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254 TStringCollection.GetItem . . . . . . . . . . . . . . . . . . . . . . . . 254 TStringCollection.Compare . . . . . . . . . . . . . . . . . . . . . . . 254 TStringCollection.FreeItem . . . . . . . . . . . . . . . . . . . . . . . 255 TStringCollection.PutItem . . . . . . . . . . . . . . . . . . . . . . . . 255 11.13TStrCollection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255 TStrCollection.GetItem . . . . . . . . . . . . . . . . . . . . . . . . . 256 13 CONTENTS TStrCollection.Compare . . . . . . . . . . . . . . . . . . . . . . . . . 256 TStrCollection.FreeItem . . . . . . . . . . . . . . . . . . . . . . . . . 257 TStrCollection.PutItem . . . . . . . . . . . . . . . . . . . . . . . . . 257 11.14TUnSortedStrCollection . . . . . . . . . . . . . . . . . . . . . . . . . 257 TUnSortedStrCollection.Insert . . . . . . . . . . . . . . . . . . . . . 258 11.15TResourceCollection . . . . . . . . . . . . . . . . . . . . . . . . . . . 258 TResourceCollection.KeyOf . . . . . . . . . . . . . . . . . . . . . . . 259 TResourceCollection.GetItem . . . . . . . . . . . . . . . . . . . . . . 259 TResourceCollection.FreeItem . . . . . . . . . . . . . . . . . . . . . . 259 TResourceCollection.PutItem . . . . . . . . . . . . . . . . . . . . . . 260 11.16TResourceFile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 260 TResourceFile Fields . . . . . . . . . . . . . . . . . . . . . . . . . . . 260 TResourceFile.Init . . . . . . . . . . . . . . . . . . . . . . . . . . . . 260 TResourceFile.Done . . . . . . . . . . . . . . . . . . . . . . . . . . . 261 TResourceFile.Count . . . . . . . . . . . . . . . . . . . . . . . . . . . 261 TResourceFile.KeyAt . . . . . . . . . . . . . . . . . . . . . . . . . . 261 TResourceFile.Get . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261 TResourceFile.SwitchTo . . . . . . . . . . . . . . . . . . . . . . . . . 261 TResourceFile.Flush . . . . . . . . . . . . . . . . . . . . . . . . . . . 262 TResourceFile.Delete . . . . . . . . . . . . . . . . . . . . . . . . . . . 262 TResourceFile.Put . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262 11.17TStringList . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262 TStringList.Load . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263 TStringList.Done . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263 TStringList.Get . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263 11.18TStrListMaker . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263 TStrListMaker.Init . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264 TStrListMaker.Done . . . . . . . . . . . . . . . . . . . . . . . . . . . 264 TStrListMaker.Put . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264 TStrListMaker.Store . . . . . . . . . . . . . . . . . . . . . . . . . . . 264 12 The PRINTER unit. 265 12.1 Types, Constants and variables : . . . . . . . . . . . . . . . . . . . . 265 12.2 Procedures and functions . . . . . . . . . . . . . . . . . . . . . . . . 265 AssignLst . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 265 13 The SOCKETS unit. 267 13.1 Types, Constants and variables : . . . . . . . . . . . . . . . . . . . . 267 13.2 Functions and Procedures . . . . . . . . . . . . . . . . . . . . . . . . 268 Accept . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 268 Accept . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270 14 CONTENTS Accept . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270 Accept . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270 Bind . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270 Bind . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 271 Connect . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 271 Connect . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 272 Connect . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 272 Connect . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 272 GetPeerName . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273 GetSocketName . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274 GetSocketOptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274 Listen . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274 Recv . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275 Send . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275 SetSocketOptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276 Shutdown . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276 Sock2File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276 Sock2Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277 Socket . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277 SocketPair . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277 Str2UnixSockAddr . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277 14 The STRINGS unit. 279 14.1 Functions and procedures. . . . . . . . . . . . . . . . . . . . . . . . . 279 StrAlloc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279 StrCat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279 StrComp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 280 StrCopy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 280 StrDispose . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281 StrECopy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281 StrEnd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 282 StrIComp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 282 StrLCat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283 StrLComp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283 StrLCopy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284 StrLen . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284 StrLIComp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285 StrLower . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285 StrMove . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 286 StrNew . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 286 15 CONTENTS StrPas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287 StrPCopy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287 StrPos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 288 StrRScan . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 288 StrScan . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 288 StrUpper . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 289 15 The SYSUTILS unit. 290 15.1 Constants and types . . . . . . . . . . . . . . . . . . . . . . . . . . . 290 15.2 Date and time functions . . . . . . . . . . . . . . . . . . . . . . . . . 293 Date and time formatting characters . . . . . . . . . . . . . . . . . . 293 TDateTime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294 Date . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294 DateTimeToFileDate . . . . . . . . . . . . . . . . . . . . . . . . . . . 295 DateTimeToStr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295 DateTimeToString . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295 DateTimeToSystemTime . . . . . . . . . . . . . . . . . . . . . . . . . 296 DateTimeToTimeStamp . . . . . . . . . . . . . . . . . . . . . . . . . 297 DateToStr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297 DayOfWeek . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298 DecodeDate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298 DecodeTime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 299 EncodeDate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 299 EncodeTime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 300 FileDateToDateTime . . . . . . . . . . . . . . . . . . . . . . . . . . . 300 FormatDateTime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 301 IncMonth . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 301 IsLeapYear . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302 MSecsToTimeStamp . . . . . . . . . . . . . . . . . . . . . . . . . . . 302 Now . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 303 StrToDate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 303 StrToDateTime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 304 StrToTime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305 SystemTimeToDateTime . . . . . . . . . . . . . . . . . . . . . . . . . 305 Time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 306 TimeStampToDateTime . . . . . . . . . . . . . . . . . . . . . . . . . 306 TimeStampToMSecs . . . . . . . . . . . . . . . . . . . . . . . . . . . 307 TimeToStr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 307 15.3 Disk functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 307 AddDisk (Linux only) . . . . . . . . . . . . . . . . . . . . . . . . . . 307 16 CONTENTS CreateDir . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 308 DiskFree . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 308 DiskSize . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 309 GetCurrentDir . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310 RemoveDir . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310 SetCurrentDir . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310 15.4 File handling functions . . . . . . . . . . . . . . . . . . . . . . . . . . 311 ChangeFileExt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311 DeleteFile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311 DoDirSeparators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311 ExpandFileName . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312 ExpandUNCFileName . . . . . . . . . . . . . . . . . . . . . . . . . . 313 ExtractFileDir . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313 ExtractFileDrive . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313 ExtractFileExt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 314 ExtractFileName . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 314 ExtractFilePath . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 314 ExtractRelativePath . . . . . . . . . . . . . . . . . . . . . . . . . . . 315 FileAge . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315 FileClose . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316 FileCreate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316 FileExists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317 FileGetAttr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317 FileGetDate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 318 FileOpen . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 319 FileRead . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 319 FileSearch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 320 FileSeek . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 320 FileSetAttr (Not on Linux) . . . . . . . . . . . . . . . . . . . . . . . 321 FileSetDate (Not on Linux) . . . . . . . . . . . . . . . . . . . . . . . 321 FileTruncate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 321 FileWrite . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 322 FindClose . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 322 FindFirst . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 322 FindNext . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323 GetDirs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323 RenameFile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 324 SetDirSeparators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 324 15.5 PChar functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 325 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 325 17 CONTENTS StrAlloc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 326 StrBufSize . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 326 StrDispose . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 327 StrPCopy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 327 StrPLCopy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 327 StrPas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 327 15.6 String handling functions . . . . . . . . . . . . . . . . . . . . . . . . 328 AdjustLineBreaks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 328 AnsiCompareStr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 328 AnsiCompareText . . . . . . . . . . . . . . . . . . . . . . . . . . . . 329 AnsiExtractQuotedStr . . . . . . . . . . . . . . . . . . . . . . . . . . 330 AnsiLastChar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330 AnsiLowerCase . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 331 AnsiQuotedStr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 331 AnsiStrComp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 332 AnsiStrIComp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333 AnsiStrLastChar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333 AnsiStrLComp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 334 AnsiStrLIComp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335 AnsiStrLower . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 336 AnsiStrUpper . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 336 AnsiUpperCase . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 337 AppendStr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 337 AssignStr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 338 BCDToInt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 338 CompareMem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 339 CompareStr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 339 CompareText . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 340 DisposeStr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 341 FloatToStr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 341 FloatToStrF . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 342 FloatToText . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 344 FmtStr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 345 Format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 345 FormatBuf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351 IntToHex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351 IntToStr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 352 IsValidIdent . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 352 LeftStr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353 LoadStr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353 18 CONTENTS LowerCase . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353 NewStr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 354 QuotedStr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 354 RightStr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355 StrFmt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355 StrLFmt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355 StrToInt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 356 StrToIntDef . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 357 Trim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 357 TrimLeft . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 358 TrimRight . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 358 UpperCase . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359 19 CONTENTS About this guide This document describes all constants, types, variables, functions and procedures as they are declared in the units that come standard with Free Pascal. Throughout this document, we will refer to functions, types and variables with typewriter font. Functions and procedures gave their own subsections, and for each function or procedure we have the following topics: Declaration The exact declaration of the function. Description What does the procedure exactly do ? Errors What errors can occur. See Also Cross references to other related functions/commands. The cross-references come in two flavors: * References to other functions in this manual. In the printed copy, a number will appear after this reference. It refers to the page where this function is explained. In the on-line help pages, this is a hyperlink, on which you can click to jump to the declaration. * References to Unix manual pages. (For Linux related things only) they are printed in typewriter font, and the number after it is the Unix manual section. The chapters are ordered alphabetically. The functions and procedures in most cases also, but don't count on it. Use the table of contents for quick lookup. 20 Chapter 1 The CRT unit. This chapter describes the CRT unit for Free Pascal, both under dos and linux. The unit was first written for dos by Florian kl¨ampfl. The unit was ported to linux by Mark May1, and enhanced by Micha¨el Van Canneyt and Peter Vreman. It works on the linux console, and in xterm and rxvt windows under X-Windows. The functionality for both is the same, except that under linux the use of an early implementation (versions 0.9.1 an earlier of the compiler) the crt unit automatically cleared the screen at program startup. This chapter is divided in two sections. * The first section lists the pre-defined constants, types and variables. * The second section describes the functions which appear in the interface part of the CRT unit. 1.1 Types, Variables, Constants Color definitions : Black = 0; Blue = 1; Green = 2; Cyan = 3; Red = 4; Magenta = 5; Brown = 6; LightGray = 7; DarkGray = 8; LightBlue = 9; LightGreen = 10; LightCyan = 11; LightRed = 12; LightMagenta = 13; Yellow = 14; White = 15; Blink = 128; Miscellaneous constants 1Current e-mail address mmay@dnaco.net 21 1.2. PROCEDURES AND FUNCTIONS TextAttr: Byte = $07; TextChar: Char = ' '; CheckBreak: Boolean = True; CheckEOF: Boolean = False; CheckSnow: Boolean = False; DirectVideo: Boolean = False; LastMode: Word = 3; WindMin: Word = $0; WindMax: Word = $184f; ScreenWidth = 80; ScreenHeight = 25; Some variables for compatibility with Turbo Pascal. However, they're not used by Free Pascal. varcheckbreak : boolean; checkeof : boolean; checksnow : boolean; The following constants define screen modes on a dos system: Const bw40 = 0; co40 = 1; bw80 = 2; co80 = 3; mono = 7; The TextAttr variable controls the attributes with which characters are written to screen. var TextAttr : byte; The DirectVideo variable controls the writing to the screen. If it is True, the the cursor is set via direct port access. If False, then the BIOS is used. This is defined under dos only. var DirectVideo : Boolean; The Lastmode variable tells you which mode was last selected for the screen. It is defined on dos only. var lastmode : Word; 1.2 Procedures and Functions AssignCrt Declaration: Procedure AssignCrt (Var F: Text); Description: Assigns a file F to the console. Everything written to the file F goes to the console instead. If the console contains a window, everything is written to the window instead. 22 1.2. PROCEDURES AND FUNCTIONS Errors: None. See also: Window (31) Program Example1 ; uses Crt ; { Program to demonstrate the AssignCrt f u n c t i o n . } varF : Text ; begin AssignCrt ( F ) ; Rewrite ( F ) ; { Don ' t f o r g e t to open f o r output ! } WriteLn ( F, ' This i s w r i t t e n to the Assigned F i l e ' ) ; Close ( F ) ; end . BigCursor Declaration: Procedure BigCursor ; Description: Makes the cursor a big rectangle. Not implemented on linux. Errors: None. See also: CursorOn (24), CursorO (24) ClrEol Declaration: Procedure ClrEol ; Description: ClrEol clears the current line, starting from the cursor position, to the end of the window. The cursor doesn't move Errors: None. See also: DelLine (25), InsLine (26), ClrScr (24) Program Example9 ; uses Crt ; { Program to demonstrate the C l r E o l f u n c t i o n . } begin Write ( ' This l i n e w i l l be c l e a r e d from the ' , ' c u r s o r p o s t i o n u n t i l the r i g h t of the screen ' ) ; GotoXY(27, WhereY) ; ReadKey ; ClrEol ; WriteLn ; end . 23 1.2. PROCEDURES AND FUNCTIONS ClrScr Declaration: Procedure ClrScr ; Description: ClrScr clears the current window (using the current colors), and sets the cursor in the top left corner of the current window. Errors: None. See also: Window (31) Program Example8 ; uses Crt ; { Program to demonstrate the Clr Scr f u n c t i o n . } begin Writeln ( ' Press any key to c l e a r the screen ' ) ; ReadKey ; ClrScr ; Writeln ( ' Have fun with the c l e a r e d screen ' ) ; end . CursorO Declaration: Procedure CursorOff ; Description: Switches the cursor o (i.e. the cursor is no longer visible). Not implemented on linux. Errors: None. See also: CursorOn (24), BigCursor (23) CursorOn Declaration: Procedure CursorOn ; Description: Switches the cursor on. Not implemented on linux. Errors: None. See also: BigCursor (23), CursorO (24) Delay Declaration: Procedure Delay (DTime: Word); Description: Delay waits a specified number of milliseconds. The number of specified seconds is an approximation, and may be o a lot, if system load is high. Errors: None See also: Sound (29), NoSound (28) 24 1.2. PROCEDURES AND FUNCTIONS Program Example15 ; uses Crt ; { Program to demonstrate the Delay f u n c t i o n . } vari : longint ; begin WriteLn ( ' Counting Down' ) ; for i :=10 downto 1 do begin WriteLn ( i ) ; Delay ( 1 0 0 0 ) ; {Wait one second } end ; WriteLn ( 'BOOM! ! ! ' ) ; end . DelLine Declaration: Procedure DelLine ; Description: DelLine removes the current line. Lines following the current line are scrolled 1 line up, and an empty line is inserted at the bottom of the current window. The cursor doesn't move. Errors: None. See also: ClrEol (23), InsLine (26), ClrScr (24) Program Example10 ; uses Crt ; { Program to demonstrate the I n s L i n e f u n c t i o n . } begin ClrScr ; WriteLn ; WriteLn ( ' Line 1' ) ; WriteLn ( ' Line 2' ) ; WriteLn ( ' Line 2' ) ; WriteLn ( ' Line 3' ) ; WriteLn ; WriteLn ( ' Oops , Line 2 i s l i s t e d twice , ' , ' l e t ' ' s d e l e t e the l i n e at the c u r s o r p o s t i o n ' ) ; GotoXY ( 1 , 3 ) ; ReadKey ; DelLine ; GotoXY( 1 , 1 0 ) ; end . GotoXY Declaration: Procedure GotoXY (X: Byte; Y: Byte); 25 1.2. PROCEDURES AND FUNCTIONS Description: Positions the cursor at (X,Y), X in horizontal, Y in vertical direction relative to the origin of the current window. The origin is located at (1,1), the upper-left corner of the window. Errors: None. See also: WhereX (30), WhereY (31), Window (31) Program Example6 ; uses Crt ; { Program to demonstrate the GotoXY f u n c t i o n . } begin ClrScr ; GotoXY( 1 0 , 1 0 ) ; Write ( ' 1 0 , 1 0 ' ) ; GotoXY( 7 0 , 2 0 ) ; Write ( ' 7 0 , 2 0 ' ) ; GotoXY( 1 , 2 2 ) ; end . HighVideo Declaration: Procedure HighVideo ; Description: HighVideo switches the output to highlighted text. (It sets the high intensity bit of the video attribute) Errors: None. See also: TextColor (30), TextBackground (29), LowVideo (27), NormVideo (28) Program Example14 ; uses Crt ; { Program to demonstrate the LowVideo , HighVideo , NormVideo f u n c t i o n s . } begin LowVideo ; WriteLn ( ' This i s w r i t t e n with LowVideo ' ) ; HighVideo ; WriteLn ( ' This i s w r i t t e n with HighVideo ' ) ; NormVideo ; WriteLn ( ' This i s w r i t t e n with NormVideo ' ) ; end . InsLine Declaration: Procedure InsLine ; Description: InsLine inserts an empty line at the current cursor position. Lines following the current line are scrolled 1 line down, causing the last line to disappear from the window. The cursor doesn't move. 26 1.2. PROCEDURES AND FUNCTIONS Errors: None. See also: ClrEol (23), DelLine (25), ClrScr (24) Program Example10 ; uses Crt ; { Program to demonstrate the I n s L i n e f u n c t i o n . } begin ClrScr ; WriteLn ; WriteLn ( ' Line 1' ) ; WriteLn ( ' Line 3' ) ; WriteLn ; WriteLn ( ' Oops , f o r g o t Line 2, l e t ' ' s i n s e r t at the c u r s o r p o s t i o n ' ) ; GotoXY ( 1 , 3 ) ; ReadKey ; I n s L i n e ; Write ( ' Line 2' ) ; GotoXY( 1 , 1 0 ) ; end . KeyPressed Declaration: Function KeyPressed : Boolean; Description: The Keypressed function scans the keyboard bu er and sees if a key has been pressed. If this is the case, True is returned. If not, False is returned. The Shift, Alt, Ctrl keys are not reported. The key is not removed from the bu er, and can hence still be read after the KeyPressed function has been called. Errors: None. See also: ReadKey (28) Program Example2 ; uses Crt ; { Program to demonstrate the KeyPressed f u n c t i o n . } begin WriteLn ( ' Waiting u n t i l a key i s p r es s ed ' ) ; repeat u n t i l KeyPressed ; { The key i s not Read , so i t should a l s o be outputted at the commandline } end . LowVideo Declaration: Procedure LowVideo ; Description: LowVideo switches the output to non-highlighted text. (It clears the high intensity bit of the video attribute) 27 1.2. PROCEDURES AND FUNCTIONS Errors: None. See also: TextColor (30), TextBackground (29), HighVideo (26), NormVideo (28) For an example, see HighVideo (26) NormVideo Declaration: Procedure NormVideo ; Description: NormVideo switches the output to the defaults, read at startup. (The defaults are read from the cursor position at startup) Errors: None. See also: TextColor (30), TextBackground (29), LowVideo (27), HighVideo (26) For an example, see HighVideo (26) NoSound Declaration: Procedure NoSound ; Description: Stops the speaker sound. This is not supported in linux Errors: None. See also: Sound (29) Program Example16 ; uses Crt ; { Program to demonstrate the Sound and NoSound f u n c t i o n . } vari : longint ; begin WriteLn ( ' You w i l l hear some tones from your speaker ' ) ; while ( i <15000) do begin inc ( i , 5 0 0 ) ; Sound ( i ) ; Delay ( 1 0 0 ) ; end ; WriteLn ( ' Quiet now ! ' ) ; NoSound ; { Stop n o i s e } end . ReadKey Declaration: Function ReadKey : Char; 28 1.2. PROCEDURES AND FUNCTIONS Description: The ReadKey function reads 1 key from the keyboard bu er, and returns this. If an extended or function key has been pressed, then the zero ASCII code is returned. You can then read the scan code of the key with a second ReadKey call. Remark. Key mappings under Linux can cause the wrong key to be reported by ReadKey, so caution is needed when using ReadKey. Errors: None. See also: KeyPressed (27) Program Example3 ; uses Crt ; { Program to demonstrate the ReadKey f u n c t i o n . } varch : char ; begin writeln ( ' Press Left / Right , Esc=Quit ' ) ; repeat ch :=ReadKey ; case ch of #0 : begin ch :=ReadKey ; {Read ScanCode } case ch of #75 : WriteLn ( ' Left ' ) ; #77 : WriteLn ( ' Right ' ) ; end ; end ; #27 : WriteLn ( ' ESC' ) ; end ; u n t i l ch=#27 { Esc } end . Sound Declaration: Procedure Sound (hz : word); Description: Sounds the speaker at a frequency of hz. This is not supported in linux Errors: None. See also: NoSound (28) TextBackground Declaration: Procedure TextBackground (CL: Byte); Description: TextBackground sets the background color to CL. CL can be one of the predefined color constants. Errors: None. See also: TextColor (30), HighVideo (26), LowVideo (27), NormVideo (28) 29 1.2. PROCEDURES AND FUNCTIONS Program Example13 ; uses Crt ; { Program to demonstrate the TextBackground f u n c t i o n . } begin TextColor ( White ) ; WriteLn ( ' This i s w r i t t e n in with the d e f a u l t background c o l o r ' ) ; TextBackground ( Green ) ; WriteLn ( ' This i s w r i t t e n in with a Green background ' ) ; TextBackground ( Brown ) ; WriteLn ( ' This i s w r i t t e n in with a Brown background ' ) ; TextBackground ( Black ) ; WriteLn ( ' Back with a black background ' ) ; end . TextColor Declaration: Procedure TextColor (CL: Byte); Description: TextColor sets the foreground color to CL. CL can be one of the predefined color constants. Errors: None. See also: TextBackground (29), HighVideo (26), LowVideo (27), NormVideo (28) Program Example12 ; uses Crt ; { Program to demonstrate the TextColor f u n c t i o n . } begin WriteLn ( ' This i s w r i t t e n in the d e f a u l t c o l o r ' ) ; TextColor ( Red ) ; WriteLn ( ' This i s w r i t t e n in Red ' ) ; TextColor ( White ) ; WriteLn ( ' This i s w r i t t e n in White ' ) ; TextColor ( LightBlue ) ; WriteLn ( ' This i s w r i t t e n in Light Blue ' ) ; end . WhereX Declaration: Function WhereX : Byte; Description: WhereX returns the current X-coordinate of the cursor, relative to the current window. The origin is (1,1), in the upper-left corner of the window. Errors: None. See also: GotoXY (25), WhereY (31), Window (31) 30 1.2. PROCEDURES AND FUNCTIONS Program Example7 ; uses Crt ; { Program to demonstrate the WhereX and WhereY f u n c t i o n s . } begin Writeln ( ' Cursor p o s t i o n : X=' , WhereX, ' Y=' , WhereY) ; end . WhereY Declaration: Function WhereY : Byte; Description: WhereY returns the current Y-coordinate of the cursor, relative to the current window. The origin is (1,1), in the upper-left corner of the window. Errors: None. See also: GotoXY (25), WhereX (30), Window (31) Program Example7 ; uses Crt ; { Program to demonstrate the WhereX and WhereY f u n c t i o n s . } begin Writeln ( ' Cursor p o s t i o n : X=' , WhereX, ' Y=' , WhereY) ; end . Window Declaration: Procedure Window (X1, Y1, X2, Y2: Byte); Description: Window creates a window on the screen, to which output will be sent. (X1,Y1) are the coordinates of the upper left corner of the window, (X2,Y2) are the coordinates of the bottom right corner of the window. These coordinates are relative to the entire screen, with the top left corner equal to (1,1) Further coordinate operations, except for the next Window call, are relative to the window's top left corner. Errors: None. See also: GotoXY (25), WhereX (30), WhereY (31), ClrScr (24) Program Example5 ; uses Crt ; { Program to demonstrate the Window f u n c t i o n . } begin ClrScr ; WriteLn ( ' Creating a window from 30,10 to 5 0 , 2 0 ' ) ; Window ( 3 0 , 1 0 , 5 0 , 2 0 ) ; WriteLn ( ' We are now w r i t i n g in t h i s small window we j u s t cr eat ed , we ' + ' can ' ' t get o u t s i d e i t when w r i t i n g long l i n e s l i k e t h i s one ' ) ; 31 1.2. PROCEDURES AND FUNCTIONS Write ( ' Press any key to c l e a r the window ' ) ; ReadKey ; ClrScr ; Write ( ' The window i s c l e a r e d , p r e s s any key to r e s t o r e to f u l l s c r e e n ' ) ; ReadKey ; { F u l l Screen i s 80 x25 } Window ( 1 , 1 , 8 0 , 2 5 ) ; Clrscr ; Writeln ( ' Back in F u l l Screen ' ) ; end . 32 Chapter 2 The DOS unit. This chapter describes the DOS unit for Free pascal, both under dos and linux. The unit was first written for dos by Florian kl¨ampfl. The unit was ported to linux by Mark May1, and enhanced by Micha¨el Van Canneyt. Under linux, some of the functionality is lost, as it is either impossible or meaningless to implement it. Other than that, the functionality for both operating systems is the same. This chapter is divided in two sections. * The first section lists the pre-defined constants, types and variables. * The second section describes the functions which appear in the interface part of the DOS unit. 2.1 Types, Variables, Constants Constants The DOS unit implements the following constants: {Bitmasks for CPU Flags} fcarry = $0001; fparity = $0004; fauxiliary = $0010; fzero = $0040; fsign = $0080; foverflow = $0800; {Bitmasks for file attribute} readonly = $01; hidden = $02; sysfile = $04; volumeid = $08; directory = $10; archive = $20; anyfile = $3F; fmclosed = $D7B0; fminput = $D7B1; fmoutput = $D7B2; fminout = $D7B3; 1Current e-mail address mmay@dnaco.net 33 2.1. TYPES, VARIABLES, CONSTANTS Types The following string types are defined for easy handling of filenames : ComStr = String[127]; { For command-lines } PathStr = String[79]; { For full path for file names } DirStr = String[67]; { For Directory and (DOS) drive string } NameStr = String[8]; { For Name of file } ExtStr = String[4]; { For Extension of file } Under linux, these strings all have length 255. {$PACKRECORDS 1} SearchRec = Record Fill : array[1..21] of byte; { Fill replaced with declarations below, for Linux} Attr : Byte; {attribute of found file} Time : LongInt; {last modify date of found file} Size : LongInt; {file size of found file} Reserved : Word; {future use} Name : String[255]; {name of found file} SearchSpec: String[255]; {search pattern} NamePos: Word; {end of path, start of name position} End; Under linux, the Fill array is replaced with the following: SearchNum: LongInt; {to track which search this is} SearchPos: LongInt; {directory position} DirPtr: LongInt; {directory pointer for reading directory} SearchType: Byte; {0=normal, 1=open will close} SearchAttr: Byte; {attribute we are searching for} Fill: Array[1..07] of Byte; {future use} This is because the searching meachanism on Unix systems is substantially di erent from dos's, and the calls have to be mimicked. const filerecnamelength = 255; type FileRec = Packed Record Handle, Mode, RecSize : longint; _private : array[1..32] of byte; UserData : array[1..16] of byte; name : array[0..filerecnamelength] of char; End; FileRec is used for internal representation of typed and untyped files. Text files are handled by the following types : const TextRecNameLength = 256; TextRecBufSize = 256; 34 2.1. TYPES, VARIABLES, CONSTANTS type TextBuf = array[0..TextRecBufSize-1] of char; TextRec = Packed Record Handle, Mode, bufsize, _private, bufpos, bufend : longint; bufptr : ^textbuf; openfunc, inoutfunc, flushfunc, closefunc : pointer; UserData : array[1..16] of byte; name : array[0..textrecnamelength-1] of char; buffer : textbuf; End; Remark that this is not binary compatible with the Turbo Pascal definition of TextRec, since the sizes of the di erent fields are di erent. Registers = record case i : integer of 0 : (ax,f1,bx,f2,cx,f3,dx,f4,bp,f5,si, f51,di,f6,ds,f7,es,f8,flags,fs,gs : word); 1 : (al,ah,f9,f10,bl,bh,f11,f12, cl,ch,f13,f14,dl,dh : byte); 2 : (eax, ebx, ecx, edx, ebp, esi, edi : longint); End; The registers type is used in the MSDos call. DateTime = record Year: Word; Month: Word; Day: Word; Hour: Word; Min: Word; Sec: word; End; The DateTime type is used in PackTime (47) and UnPackTime (49) for setting/reading file times with GetFTime (44) and SetFTime (48). Variables DosError : integer; The DosError variable is used by the procedures in the dos unit to report errors. It can have the following values : 35 2.2. FUNCTIONS AND PROCEDURES 2 File not found. 3 path not found. 5 Access denied. 6 Invalid handle. 8 Not enough memory. 10 Invalid environment. 11 Invalid format. 18 No more files. Other values are possible, but are not documented. 2.2 Functions and Procedures AddDisk Declaration: Procedure AddDisk (Const S : String); Description: AddDisk adds a filename S to the internal list of disks. It is implemented for linux only. This list is used to determine which disks to use in the DiskFree (36) and DiskSize (37) calls. The DiskFree (36) and DiskSize (37) functions need a file on the specified drive, since this is required for the statfs system call. The names are added sequentially. The dos initialization code presets the first three disks to: *'.' for the current drive, *'/fd0/.' for the first floppy-drive. *'/fd1/.' for the second floppy-drive. *'/' for the first hard disk. The first call to AddDisk will therefore add a name for the second harddisk, The second call for the third drive, and so on until 23 drives have been added (corre- sponding to drives 'D:' to 'Z:') Errors: None See also: DiskFree (36), DiskSize (37) DiskFree Declaration: Function DiskFree (Drive: byte) : longint; Description: DiskFree returns the number of free bytes on a disk. The parameter Drive indi- cates which disk should be checked. This parameter is 1 for floppy a:, 2 for floppy b:, etc. A value of 0 returns the free space on the current drive. Typically, the free space is the size of a disk block, multiplied by the number of free blocks on the disk. For linux only: The diskfree and disksize functions need a file on the specified drive, since this is required for the statfs system call. These filenames are set in the initialization of the dos unit, and have been preset to : *'.' for the current drive, *'/fd0/.' for the first floppy-drive. *'/fd1/.' for the second floppy-drive. *'/' for the first hard disk. 36 2.2. FUNCTIONS AND PROCEDURES There is room for 1-26 drives. You can add a drive with the AddDisk (36) procedure. These settings can be coded in dos.pp, in the initialization part. Errors: -1 when a failure occurs, or an invalid drivenr is given. See also: DiskSize (37), AddDisk (36) Program Example6 ; uses Dos ; { Program to demonstrate the DiskSiz e and DiskFree f u n c t i o n . } begin WriteLn ( ' This p a r t i t i o n s i z e has ' , DiskSize ( 0 ) , ' bytes ' ) ; WriteLn ( ' C u r r e n t l y ' , DiskFree ( 0 ) , ' bytes are f r e e ' ) ; end . DiskSize Declaration: Function DiskSize (Drive: byte) : longint; Description: DiskSize returns the total size (in bytes) of a disk. The parameter Drive indicates which disk should be checked. This parameter is 1 for floppy a:, 2 for floppy b:, etc. A value of 0 returns the size of the current drive. For linux only: The diskfree and disksize functions need a file on the specified drive, since this is required for the statfs system call. These filenames are set in the initialization of the dos unit, and have been preset to : *'.' for the current drive, *'/fd0/.' for the first floppy-drive. *'/fd1/.' for the second floppy-drive. *'/' for the first hard disk. There is room for 1-26 drives. You can add a drive with the AddDisk (36) procedure. These settings can be coded in dos.pp, in the initialization part. Errors: -1 when a failure occurs, or an invalid drive number is given. See also: DiskFree (36), AddDisk (36) For an example, see DiskFree (36). DosExitCode Declaration: Function DosExitCode : Word; Description: DosExitCode contains (in the low byte) the exit-code of a program executed with the Exec call. Errors: None. See also: Exec (39) 37 2.2. FUNCTIONS AND PROCEDURES Program Example5 ; uses Dos ; { Program to demonstrate the Exec and DosExitCode f u n c t i o n . } begin {$IFDEF LINUX} WriteLn ( ' Executing / bin / l s -la ' ) ; Exec ( '/ bin / l s ' , '- la ' ) ; {$ELSE} WriteLn ( ' Executing Dir ' ) ; Exec ( GetEnv ( ' COMSPEC' ) , '/ C d i r ' ) ; {$ENDIF} WriteLn ( ' Program r e t u r n e d with ExitCode ' , DosExitCode ) ; end . DosVersion Declaration: Function DosVersion : Word; Description: DosVersion returns the dos version number. On linux systems, it returns the Linux version (The first 2 numbers, e.g Linux version 2.1.76 will give you DosVersion 2.1) Errors: None. See also: Program Example1 ; uses Dos ; { Program to demonstrate the DosVersion f u n c t i o n . } varOS : st r in g [ 3 2 ] ; Version : word ; begin {$IFDEF LINUX} OS:= ' Linux ' ; {$ENDIF} {$IFDEF DOS} OS:= ' Dos ' ; {$ENDIF} Version := DosVersion ; WriteLn ( ' Current ' , OS, ' v e r s i o n i s ' , Lo( Version ) , ' . ' , Hi ( Version ) ) ; end . EnvCount Declaration: Function EnvCount : longint; Description: EnvCount returns the number of environment variables. Errors: None. See also: EnvStr (39), Dos:GetEnv (43) 38 2.2. FUNCTIONS AND PROCEDURES EnvStr Declaration: Function EnvStr (Index: integer) : string; Description: EnvStr returns the Index-th Name=Value pair from the list of environment vari- ables. The index of the first pair is zero. Errors: The length is limited to 255 characters. This may cause problems under linux. The linux unit solves this problem. See also: EnvCount (38), Dos:GetEnv (43) Program Example13 ; uses Dos ; { Program to demonstrate the EnvCount and EnvStr f u n c t i o n . } vari : Longint ; begin WriteLn ( ' Current Environment i s : ' ) ; for i :=1 to EnvCount do WriteLn ( EnvStr ( i ) ) ; end . Exec Declaration: Procedure Exec (const Path: pathstr; const ComLine: comstr); Description: Exec executes the program in Path, with the options given by ComLine. After the program has terminated, the procedure returns. The Exit value of the program can be consulted with the DosExitCode function. Errors: Errors are reported in DosError. See also: DosExitCode (37) For an example, see DosExitCode (37) FExpand Declaration: Function FExpand (const path: pathstr) : pathstr; Description: FExpand takes its argument and expands it to a complete filename, i.e. a filename starting from the root directory of the current drive, prepended with the drive-letter (under dos). The resulting name is converted to uppercase on dos systems. Under linux, the name is left as it is. (filenames are case sensitive under Unix) Errors: FSplit (42) Program Example5 ; uses Dos ; { Program to demonstrate the Exec and DosExitCode f u n c t i o n . } begin 39 2.2. FUNCTIONS AND PROCEDURES {$IFDEF LINUX} WriteLn ( ' Executing / bin / l s -la ' ) ; Exec ( '/ bin / l s ' , '- la ' ) ; {$ELSE} WriteLn ( ' Executing Dir ' ) ; Exec ( GetEnv ( ' COMSPEC' ) , '/ C d i r ' ) ; {$ENDIF} WriteLn ( ' Program r e t u r n e d with ExitCode ' , DosExitCode ) ; end . See also: FindClose Declaration: Procedure FindClose (Var F: SearchRec); Description: linux only Under linux, the findfirst/findnext calls have to be mimicked. An internal table of file descriptors is kept. When using di erent searchrecs at the same time, the system may run out of file descriptors for directories. The linux implementation of the dos unit therefore keeps a table of open directories, and when the table is full, closes one of the directories, and reopens another. This system is adequate but slow if you use a lot of searchrecs. So, to speed up the findfirst/findnext system, the FindClose call was implemented. When you don't need a searchrec any more, you can tell this to the dos unit by issuing a FindClose call. The directory which is kept open for this searchrec is then closed, and the table slot freed. It is recommended to use the linux call Glob when looking for files. Errors: None. See also: Glob (167). FindFirst Declaration: Procedure FindFirst (const Path: pathstr; Attr: word; var F: SearchRec); Description: FindFirst searches the file specified in Path, checks the atrributes specified in Attr. It returns a SearchRec record for further searching in F. Path can contain the wildcard characters ? (matches any single character) and * (matches 0 ore more arbitrary characters). In this case FindFirst will return the first file which matches the specified criteria. If DosError is di erent from zero, no file(s) matching the criteria was(were) found. Errors: Errors are reported in DosError. See also: FindNext (41), FindClose (40) Program Example7 ; uses Dos ; { Program to demonstrate the F i n d F i r s t and FindNext f u n c t i o n . } varDir : SearchRec ; begin 40 2.2. FUNCTIONS AND PROCEDURES FindFirst ( ' . ' , $20 , Dir ) ; WriteLn ( ' FileName ' +Space ( 3 2 ) , ' F i l e S i z e ' : 9 ) ; while ( DosError =0) do begin Writeln ( Dir . Name+Space (40- Length ( Dir . Name) ) , Dir . Size : 9 ) ; FindNext ( Dir ) ; end ; FindClose ( Dir ) ; end . FindNext Declaration: Procedure FindNext (var f: searchRec); Description: FindNext takes as an argument a SearchRec from a previous FindNext call, or a FindFirst call, and tries to find another file which matches the criteria, specified in the FindFirst call. If DosError is di erent from zero, no more files matching the criteria were found. Errors: DosError is used to report errors. See also: FindFirst (40), FindClose (40) For an example, see FindFirst (40). FSearch Declaration: Function FSearch (Path: pathstr; DirList: string) : pathstr; Description: FSearch searches the file Path in all directories listed in DirList. The full name of the found file is returned. DirList must be a list of directories, separated by semi-colons (or colons under linux). When no file is found, an empty string is returned. Errors: None. See also: FExpand (39) Program Example10 ; uses Dos ; { Program to demonstrate the FSearch f u n c t i o n . } vars : string ; begin s := FSearch ( ParamStr ( 1 ) , GetEnv ( ' PATH' ) ) ; i f s=' ' then WriteLn ( ParamStr ( 1 ) , ' not Found in PATH' ) else Writeln ( ParamStr ( 1 ) , ' Found in PATH at ' , s ) ; end . 41 2.2. FUNCTIONS AND PROCEDURES FSplit Declaration: Procedure FSplit (path: pathstr; var dir: dirstr; var name: namestr; var ext: extstr); Description: FSplit splits a full file name into 3 parts : A Path, a Name and an extension (in ext.) Under linux, the extension is taken to be all letters after the last dot (.). Errors: None. See also: FSearch (41) Program Example12 ; uses Dos ; { Program to demonstrate the F S p l i t f u n c t i o n . } varPath,Name, Ext : string ; begin F S p l i t ( ParamStr ( 1 ) , Path , Name, Ext ) ; WriteLn ( ' S p l i t t e d ' , ParamStr ( 1 ) , ' in : ' ) ; WriteLn ( ' Path : ' , Path ) ; WriteLn ( ' Name : ' , Name) ; WriteLn ( ' Extension : ' , Ext ) ; end . GetCBreak Declaration: Procedure GetCBreak (var breakvalue: boolean); Description: GetCBreak gets the status of CTRL-Break checking under dos. When BreakValue is false, then dos only checks for the CTRL-Break key-press when I/O is per- formed. When it is set to True, then a check is done at every system call. Errors: Under Linux, this exists but is not implemented, i.e. the call does nothing. See also: SetCBreak (47) GetDate Declaration: Procedure GetDate (var year, month, mday, wday: word); Description: GetDate returns the system's date. Year is a number in the range 1980..2099.mday is the day of the month, wday is the day of the week, starting with Sunday as day 0. Errors: None. See also: GetTime (45),SetDate (48) Program Example2 ; uses Dos ; { Program to demonstrate the GetDate f u n c t i o n . } 42 2.2. FUNCTIONS AND PROCEDURES const DayStr : array [ 0 . . 6 ] of st rin g [3]=( ' Sun ' , ' Mon' , ' Tue ' , ' Wed' , ' Thu ' , ' F r i ' , ' Sat ' ) ; MonthStr : array [ 1 . . 1 2 ] of str ing [3]=( ' Jan ' , ' Feb ' , ' Mar ' , ' Apr ' , ' May' , ' Jun ' , ' Jul ' , ' Aug ' , ' Sep ' , ' Oct ' , ' Nov ' , ' Dec ' ) ; varYear ,Month,Day,WDay : word; begin GetDate ( Year , Month , Day , WDay) ; WriteLn ( ' Current date ' ) ; WriteLn ( DayStr [ WDay] , ' , ' , Day , ' ' , MonthStr [ Month ] , ' ' , Year , ' . ' ) ; end . GetEnv Declaration: Function GetEnv (EnvVar: String) : String; Description: Getenv returns the value of the environment variable EnvVar. Under linux, case is important when looking for EnvVar. When there is no environment variable EnvVar defined, an empty string is returned. Errors: None. See also: EnvCount (38), EnvStr (39) Program Example14 ; uses Dos ; { Program to demonstrate the GetEnv f u n c t i o n . } begin WriteLn ( ' Current PATH i s ' , GetEnv ( ' PATH' ) ) ; end . GetFAttr Declaration: Procedure GetFAttr (var F; var Attr: word); Description: GetFAttr returns the file attributes of the file-variable f. F can be a untyped or typed file, or of type Text. f must have been assigned, but not opened. The attributes can be examined with the following constants : *ReadOnly = 01h *Hidden = 02h *SysFile = 04h *VolumeId = 08h *Directory = 10h *Archive = 20h *AnyFile = 3fh Under linux, supported attributes are: *Directory *ReadOnly if the current process doesn't have access to the file. 43 2.2. FUNCTIONS AND PROCEDURES *Hidden for files whose name starts with a dot ('.'). Errors: Errors are reported in DosError See also: SetFAttr (48) Program Example8 ; uses Dos ; { Program to demonstrate the GetFAttr f u n c t i o n . } varAttr : Word; f : File ; begin Assign ( f , ParamStr ( 1 ) ) ; GetFAttr ( f , Attr ) ; WriteLn ( ' F i l e ' , ParamStr ( 1 ) , ' has a t t r i b u t e ' , Attr ) ; i f ( Attr and $20 )<>0 then WriteLn ( '- Archive ' ) ; i f ( Attr and $10 )<>0 then WriteLn ( '- D i r e c t o r y ' ) ; i f ( Attr and $4 )<>0 then WriteLn ( '- Read-Only ' ) ; i f ( Attr and $2 )<>0 then WriteLn ( '- System ' ) ; i f ( Attr and $1 )<>0 then WriteLn ( '- Hidden ' ) ; end . GetFTime Declaration: Procedure GetFTime (var F; var Time: longint); Description: GetFTime returns the modification time of a file. This time is encoded and must be decoded with UnPackTime. F must be a file type, which has been assigned, and opened. Errors: Errors are reported in DosError See also: SetFTime (48), PackTime (47),UnPackTime (49) Program Example9 ; uses Dos ; { Program to demonstrate the GetFTime f u n c t i o n . } Function L0 (w: word ) : st ring ; vars : string ; begin Str (w, s ) ; i f w<10 then L0:= ' 0 ' +s else L0:= s ; end ; varf : File ; 44 2.2. FUNCTIONS AND PROCEDURES Time : Longint ; DT : DateTime ; begin Assign ( f , ParamStr ( 1 ) ) ; Reset ( f ) ; GetFTime ( f , Time ) ; Close ( f ) ; UnPackTime ( Time, DT) ; Write ( ' F i l e ' , ParamStr ( 1 ) , ' i s l a s t modified on ' ) ; Writeln ( L0 (DT. Month ) , '-' , L0 (DT. Day ) , '-' , DT. Year , ' at ' , L0 (DT. Hour ) , ' : ' , L0 (DT. Min ) ) ; end . GetIntVec Declaration: Procedure GetIntVec (IntNo: byte; var Vector: pointer); Description: GetIntVec returns the address of interrupt vector IntNo. Errors: None. Under linux, this call exists bout isn't implemented, i.e. it does nothing. See also: SetIntVec (48) GetTime Declaration: Procedure GetTime (var hour, minute, second, sec100: word); Description: GetTime returns the system's time. Hour is a on a 24-hour time scale. sec100 is in hundredth of a second. Errors: None. See also: GetDate (42), SetTime (49) Program Example3 ; uses Dos ; { Program to demonstrate the GetTime f u n c t i o n . } Function L0 (w: word ) : str ing ; vars : string ; begin Str (w, s ) ; i f w<10 then L0:= ' 0 ' +s else L0:= s ; end ; varHour,Min, Sec , HSec : word; begin GetTime ( Hour , Min , Sec , HSec ) ; WriteLn ( ' Current time ' ) ; 45 2.2. FUNCTIONS AND PROCEDURES WriteLn ( L0 ( Hour ) , ' : ' , L0 ( Min ) , ' : ' , L0 ( Sec ) ) ; end . GetVerify Declaration: Procedure GetVerify (var verify: boolean); Description: GetVerify returns the status of the verify flag under dos. When Verify is True, then dos checks data which are written to disk, by reading them after writing. If Verify is False, then data written to disk are not verified. Errors: Under linux, Verify is always True. See also: SetVerify (49) Intr Declaration: Procedure Intr (IntNo: byte; var Regs: registers); Description: Intr executes a software interrupt number IntNo (must be between 0 and 255), with processor registers set to Regs. After the interrupt call returned, the processor registers are saved in Regs. Errors: Under linux this call does nothing, because interrupts are managed by the kernel. The only allowed interrupt is 80h, the kernel entry interrupt. See also: MSDos (46), see the linux unit. Keep Declaration: Procedure Keep (ExitCode: word); Description: Keep terminates the program, but stays in memory. This is used for TSR (Termi- nate Stay Resident) programs which catch some interrupt. ExitCode is the same parameter as the Halt function takes. Errors: Under linux, this call does nothing. See also: Halt () MSDos Declaration: Procedure MSDos (var regs: registers); Description: MSDos executes an MS-dos call (int 21h). This is the same as doing a Intr call with an interrupt number of 21h. Errors: None. See also: Intr (46) 46 2.2. FUNCTIONS AND PROCEDURES PackTime Declaration: Procedure PackTime (var T: datetime; var P: longint); Description: UnPackTime converts the date and time specified in T to a packed-time format which can be fed to SetFTime. Errors: None. See also: SetFTime (48), FindFirst (40), FindNext (41), UnPackTime (49) Program Example4 ; uses Dos ; { Program to demonstrate the PackTime and UnPackTime f u n c t i o n s . } varDT : DateTime; Time : l o n g i n t ; begin with DT do begin Year :=1998; Month :=11; Day :=11; Hour :=11; Min :=11; Sec :=11; end ; PackTime (DT, Time ) ; WriteLn ( ' Packed Time : ' , Time ) ; UnPackTime ( Time, DT) ; WriteLn ( ' Unpacked Again : ' ) ; with DT do begin WriteLn ( ' Year ' , Year ) ; WriteLn ( ' Month ' , Month ) ; WriteLn ( ' Day ' , Day ) ; WriteLn ( ' Hour ' , Hour ) ; WriteLn ( ' Min ' , Min ) ; WriteLn ( ' Sec ' , Sec ) ; end ; end . SetCBreak Declaration: Procedure SetCBreak (breakvalue: boolean); Description: SetCBreak sets the status of CTRL-Break checking under dos. When BreakValue is false, then dos only checks for the CTRL-Break key-press when I/O is per- formed. When it is set to True, then a check is done at every system call. Errors: Under Linux, this call exists but is not implemented, i.e. it does nothing. See also: GetCBreak (42) 47 2.2. FUNCTIONS AND PROCEDURES SetDate Declaration: Procedure SetDate (year,month,day: word); Description: SetDate sets the system's internal date. Year is a number between 1980 and 2099. Errors: On a linux machine, this is not implemented (allthough a procedure exists, it just doesn't do anything. The setting of the date is a root-only privilege, and is hence not implemented. See also: Dos:GetDate (42), SetTime (49) SetFAttr Declaration: Procedure SetFAttr (var F; Attr: word); Description: SetFAttr sets the file attributes of the file-variable F. F can be a untyped or typed file, or of type Text. F must have been assigned, but not opened. The attributes can be a sum of the following constants: *ReadOnly = 01h *Hidden = 02h *SysFile = 04h *VolumeId = 08h *Directory = 10h *Archive = 20h *AnyFile = 3fh Errors: Errors are reported in DosError. Under linux the call exists, but is not imple- mented, i.e. it does nothing. See also: GetFAttr (43) SetFTime Declaration: Procedure SetFTime (var F; Time: longint); Description: SetFTime sets the modification time of a file, this time is encoded and must be encoded with PackTime. F must be a file type, which has been assigned, and opened. Errors: Errors are reported in DosError See also: GetFTime (44), PackTime (47),UnPackTime (49) SetIntVec Declaration: Procedure SetIntVec (IntNo: byte; Vector: pointer); Description: SetIntVec sets interrupt vector IntNo to Vector. Vector should point to an interrupt procedure. Errors: Under linux, this call exists but is not implemented, the kernel manages all inter- rupts. See also: GetIntVec (45) 48 2.2. FUNCTIONS AND PROCEDURES SetTime Declaration: Procedure SetTime (hour,minute,second,sec100: word); Description: SetTime sets the system's internal clock. The Hour parameter is on a 24-hour time scale. Errors: this call exists, but is not implemented on linux, as setting the time is a root-only privilege. See also: Dos:GetTime (45), SetDate (48) SetVerify Declaration: Procedure SetVerify (verify: boolean); Description: SetVerify sets the status of the verify flag under dos. When Verify is True, then dos checks data which are written to disk, by reading them after writing. If Verify is False, then data written to disk are not verified. Errors: Under linux, Verify is always True. See also: SetVerify (49) SwapVectors Declaration: Procedure SwapVectors ; Description: SwapVectors swaps the contents of the internal table of interrupt vectors with the current contents of the interrupt vectors. This is called typically in before and after an Exec call. Errors: Under linux this call does nothing, as the interrupt vectors are managed by the kernel. See also: Exec (39), SetIntVec (48) UnPackTime Declaration: Procedure UnPackTime (p: longint; var T: datetime); Description: UnPackTime converts the file-modification time in p to a DateTime record. The file-modification time can be returned by GetFTime, FindFirst or FindNext calls. Errors: None. See also: GetFTime (44), FindFirst (40), FindNext (41), PackTime (47) For an example, see PackTime (47). 49 Chapter 3 The GETOPTS unit. This document describes the GETOPTS unit for Free Pascal. It was written for linux by Micha¨el Van Canneyt. It also works under DOS and Tp7. The chapter is divided in 2 sections: * The first section lists types, constants and variables from the interface part of the unit. * The second section describes the functions defined in the unit. 3.1 Types, Constants and variables : Constants No Argument=0 : Specifies that a long option does not take an argument. Required Argument=1 : Specifies that a long option needs an argument. Optional Argument=2 : Specifies that a long option optionally takes an argument. EndOfOptions=#255 : Returned by getopt, getlongopts to indicate that there are no more options. Types TOption = record Name : String; Has_arg : Integer; Flag : PChar; Value : Char; end; POption = ^TOption; The option type is used to communicate the long options to GetLongOpts. The Name field is the name of the option. Has arg specifies if the option wants an argu- ment, Flag is a pointer to a char, which is set to Value, if it is non-nil. POption is a pointer to a Option record. It is used as an argument to the GetLongOpts function. 50 3.2. PROCEDURES AND FUNCTIONS Variables OptArg:String Is set to the argument of an option, if the option needs one. Optind:Longint Is the index of the current paramstr(). When all options have been processed, optind is the index of the first non-option parameter. This is a read-only variable. Note that it can become equal to paramcount+1 OptErr:Boolean Indicates whether getopt() prints error messages. OptOpt:Char In case of an error, contains the character causing the error. 3.2 Procedures and functions GetLongOpts Declaration: Function GetLongOpts (Shortopts : String, LongOpts : POption; var Longint : Longint ) : Char; Description: Returns the next option found on the command-line, taking into account long options as well. If no more options are found, returns EndOfOptions. If the option requires an argument, it is returned in the OptArg variable. ShortOptions is a string containing all possible one-letter options. (see Getopt (51) for its description and use) LongOpts is a pointer to the first element of an array of Option records, the last of which needs a name of zero length. The function tries to match the names even partially (i.e. --app will match e.g. the append option), but will report an error in case of ambiguity. If the option needs an argument, set Has arg to Required argument, if the option optionally has an argument, set Has arg to Optional argument. If the option needs no argument, set Has arg to zero. Required arguments can be specified in two ways : 1. Pasted to the option : --option=value 2. As a separate argument : --option value Optional arguments can only be specified through the first method. Errors: see Getopt (51), getopt (3) See also: Getopt Getopt Declaration: Function Getopt (Shortopts : String) : Char; Description: Returns the next option found on the command-line. If no more options are found, returns EndOfOptions. If the option requires an argument, it is returned in the OptArg variable. ShortOptions is a string containing all possible one-letter options. If a letter is followed by a colon (:), then that option needs an argument. If a letter is followed by 2 colons, the option has an optional argument. If the first character of shortoptions is a '+' then options following a non-option are regarded as non-options (standard Unix behavior). If it is a '-', then all non-options are treated as arguments of a option with character #0. This is useful for applications that require their options in the exact order as they appear on the command-line. If the first character of shortoptions is none of the above, options and non-options are permuted, so all non-options are behind all options. This allows options and non-options to be in random order on the command line. 51 3.2. PROCEDURES AND FUNCTIONS Errors: Errors are reported through giving back a '?' character. OptOpt then gives the character which caused the error. If OptErr is True then getopt prints an error- message to stdout. See also: GetLongOpts (51), getopt (3) program t e s t o p t ; { Program to depmonstrate the getopts f u n c t i o n . } { Valid calls to this program are optex --verbose --add me --d e l e t e you optex --append --c r e a t e c h i l d optex -ab -c me -d you and so on }uses getopts ; var c : char ; o p t i o n i n d e x : Longint ; theopts : array [ 1 . . 7 ] of TOption ; begin with theopts [ 1 ] do begin name:= ' add ' ; has arg :=1; f l a g := n i l ; value :=#0; end ; with theopts [ 2 ] do begin name:= ' append ' ; has arg :=0; f l a g := n i l ; value :=#0; end ; with theopts [ 3 ] do begin name:= ' d e l e t e ' ; has arg :=1; f l a g := n i l ; value :=#0; end ; with theopts [ 4 ] do begin name:= ' verbose ' ; has arg :=0; f l a g := n i l ; value :=#0; end ; with theopts [ 5 ] do begin 52 3.2. PROCEDURES AND FUNCTIONS name:= ' c r e a t e ' ; has arg :=1; f l a g := n i l ; value := ' c ' end ; with theopts [ 6 ] do begin name:= ' f i l e ' ; has arg :=1; f l a g := n i l ; value :=#0; end ; with theopts [ 7 ] do begin name:= ' ' ; has arg :=0; f l a g := n i l ; end ; c :=#0; repeat c := g e t l o n g o p t s ( ' abc : d : 0 1 2 ' , @theopts [ 1 ] , o p t i o n i n d e x ) ; case c of ' 1 ' , ' 2 ' , ' 3 ' , ' 4 ' , ' 5 ' , ' 6 ' , ' 7 ' , ' 8 ' , ' 9 ' : begin writeln ( ' Got optind : ' , c ) end ; #0 : begin write ( ' Long option : ' , theopts [ o p t i o n i n d e x ] . name) ; i f theopts [ o p t i o n i n d e x ] . has arg >0 then writeln ( ' With value : ' , optarg ) else writeln end ; ' a ' : writeln ( ' Option a . ' ) ; ' b ' : writeln ( ' Option b . ' ) ; ' c ' : writeln ( ' Option c : ' , optarg ) ; ' d ' : writeln ( ' Option d : ' , optarg ) ; ' ? ' , ' : ' : writeln ( ' Error with opt : ' , optopt ) ; end ; { case } u n t i l c=e n d o f o p t i o n s ; i f optind <=paramcount then begin write ( ' Non o p t i o n s : ' ) ; while optind <=paramcount do begin write ( paramstr ( optind ) , ' ' ) ; inc ( optind ) end ; writeln end end . 53 Chapter 4 The GO32 unit This chapter of the documentation describe the GO32 unit for the Free Pascal com- piler under dos. It was donated by Thomas Schatzl (tom at work@geocities.com), for which my thanks. This unit was first written for dos by Florian Klaempfl. This chapter is divided in three sections. The first section is an introduction to the GO32 unit. The second section lists the pre-defined constants, types and variables. The third section describes the functions which appear in the interface part of the GO32 unit. 4.1 Introduction These docs contain information about the GO32 unit. Only the GO32V2 DPMI mode is discussed by me here due to the fact that new applications shouldn't be created with the older GO32V1 model. The former is much more advanced and better. Additionally a lot of functions only work in DPMI mode anyway. I hope the following explanations and introductions aren't too confusing at all. If you notice an error or bug send it to the FPC mailing list or directly to me. So let's get started and happy and error free coding I wish you.... Thomas Schatzl, 25. August 1998 4.2 Protected mode memory organization What is DPMI The dos Protected Mode Interface helps you with various aspects of protected mode programming. These are roughly divided into descriptor handling, access to dos memory, management of interrupts and exceptions, calls to real mode functions and other stu . Additionally it automatically provides swapping to disk for memory in- tensive applications. A DPMI host (either a Windows dos box or CWSDPMI.EXE) provides these functions for your programs. Selectors and descriptors Descriptors are a bit like real mode segments; they describe (as the name implies) a memory area in protected mode. A descriptor contains information about segment length, its base address and the attributes of it (i.e. type, access rights, ...). These 54 4.2. PROTECTED MODE MEMORY ORGANIZATION descriptors are stored internally in a so-called descriptor table, which is basically an array of such descriptors. Selectors are roughly an index into this table. Because these 'segments' can be up to 4 GB in size, 32 bits aren't su cient anymore to describe a single memory location like in real mode. 48 bits are now needed to do this, a 32 bit address and a 16 bit sized selector. The GO32 unit provides the tseginfo record to store such a pointer. But due to the fact that most of the time data is stored and accessed in the %ds selector, FPC assumes that all pointers point to a memory location of this selector. So a single pointer is still only 32 bits in size. This value represents the o set from the data segment base address to this memory location. FPC specialities The %ds and %es selector MUST always contain the same value or some system routines may crash when called. The %fs selector is preloaded with the DOSMEM- SELECTOR variable at startup, and it MUST be restored after use, because again FPC relys on this for some functions. Luckily we asm programmers can still use the %gs selector for our own purposes, but for how long ? See also: get cs (71), get ds (72), gett ss (79), allocate ldt descriptors (64), free ldt descriptor (70), segment to descriptor (85), get next selector increment value (73), get segment base address (78), set segment base address (88), set segment limit (88), create code segment alias descriptor (67) dos memory access dos memory is accessed by the predefined dosmemselector selector; the GO32 unit additionally provides some functions to help you with standard tasks, like copying memory from heap to dos memory and the likes. Because of this it is strongly recommened to use them, but you are still free to use the provided standard memory accessing functions which use 48 bit pointers. The third, but only thought for compatibility purposes, is using the mem[]-arrays. These arrays map the whole 1 Mb dos space. They shouldn't be used within new programs. To convert a segment:o set real mode address to a protected mode linear address you have to multiply the segment by 16 and add its o set. This linear address can be used in combination with the DOSMEMSELECTOR variable. See also: dosmemget (69), dosmemput (70), dosmemmove (69), dosmemfillchar (68), dosmemfillword (69), mem[]-arrays, seg move (86), seg fillchar (84), seg fillword (85). I/O port access The I/O port access is done via the various inportb (81), outportb (83) functions which are available. Additionally Free Pascal supports the Turbo Pascal PORT[]- arrays but it is by no means recommened to use them, because they're only for compatibility purposes. See also: outportb (83), inportb (81), PORT[]-arrays Processor access These are some functions to access various segment registers (%cs, %ds, %ss) which makes your work a bit easier. See also: get cs (71), get ds (72), get ss (79) 55 4.2. PROTECTED MODE MEMORY ORGANIZATION Interrupt redirection Interrupts are program interruption requests, which in one or another way get to the processor; there's a distinction between software and hardware interrupts. The former are explicitely called by an 'int' instruction and are a bit comparable to normal functions. Hardware interrupts come from external devices like the keyboard or mouse. These functions are called handlers. Handling interrupts with DPMI The interrupt functions are real-mode procedures; they normally can't be called in protected mode without the risk of an protection fault. So the DPMI host creates an interrupt descriptor table for the application. Initially all software interrupts (except for int 31h, 2Fh and 21h function 4Ch) or external hardware interrupts are simply directed to a handler that reflects the interrupt in real-mode, i.e. the DPMI host's default handlers switch the CPU to real-mode, issue the interrupt and switch back to protected mode. The contents of general registers and flags are passed to the real mode handler and the modified registers and flags are returned to the protected mode handler. Segment registers and stack pointer are not passed between modes. Protected mode interrupts vs. Real mode interrupts As mentioned before, there's a distinction between real mode interrupts and pro- tected mode interrupts; the latter are protected mode programs, while the former must be real mode programs. To call a protected mode interrupt handler, an as- sembly 'int' call must be issued, while the other is called via the realintr() or intr() function. Consequently, a real mode interrupt then must either reside in dos mem- ory (¡1MB) or the application must allocate a real mode callback address via the get rm callback() function. Creating own interrupt handlers Interrupt redirection with FPC pascal is done via the set pm interrupt() for pro- tected mode interrupts or via the set rm interrupt() for real mode interrupts. Disabling interrupts The GO32 unit provides the two procedures disable() and enable() to disable and enable all interrupts. Hardware interrupts Hardware interrupts are generated by hardware devices when something unusual happens; this could be a keypress or a mouse move or any other action. This is done to minimize CPU time, else the CPU would have to check all installed hardware for data in a big loop (this method is called 'polling') and this would take much time. A standard IBM-PC has two interrupt controllers, that are responsible for these hardware interrupts: both allow up to 8 di erent interrupt sources (IRQs, interrupt requests). The second controller is connected to the first through IRQ 2 for compatibility reasons, e.g. if controller 1 gets an IRQ 2, he hands the IRQ over to controller 2. Because of this up to 15 di erent hardware interrupt sources 56 4.2. PROTECTED MODE MEMORY ORGANIZATION can be handled. IRQ 0 through IRQ 7 are mapped to interrupts 8h to Fh and the second controller (IRQ 8 to 15) is mapped to interrupt 70h to 77h. All of the code and data touched by these handlers MUST be locked (via the various locking functions) to avoid page faults at interrupt time. Because hardware interrupts are called (as in real mode) with interrupts disabled, the handler has to enable them before it returns to normal program execution. Additionally a hardware interrupt must send an EOI (end of interrupt) command to the responsible controller; this is acomplished by sending the value 20h to port 20h (for the first controller) or A0h (for the second controller). The following example shows how to redirect the keyboard interrupt. Program K e y c l i c k ; uses c r t , go32 ; const kbdint = $9 ; var o l d i n t 9 h a n d l e r : t s e g i n f o ; newint9 handler : t s e g i n f o ; c l i c k p r o c : p o i n t e r ; {$ASMMODE DIRECT} procedure int9 handler ; assembler ; asm cli pushal movw %cs : INT9 DS, % ax movw %ax , % ds movw %ax , % es movw U GO32 DOSMEMSELECTOR, % ax movw %ax , % fs c a l l CLICKPROC popal ljmp %cs : OLDHANDLER INT9 DS : . word 0 OLDHANDLER: . long 0 . word 0 end ; procedure int9 dummy ; begin end ; procedure c l i c k e r ; begin sound (500); delay (10); nosound ; end ; procedure clicker dummy ; begin end ; procedure i n s t a l l c l i c k ; 57 4.2. PROTECTED MODE MEMORY ORGANIZATION begin clickproc := @clicker ; lock data ( c l i c k p r o c , s i z e o f ( c l i c k p r o c ) ) ; lock data ( dosmemselector , s i z e o f ( dosmemselector ) ) ; lock code ( @ c l i c k e r , l o n g i n t ( @clicker dummy )- l o n g i n t ( @ c l i c k e r ) ) ; lock code ( @int9 handler , l o n g i n t ( @int9 dummy ) - l o n g i n t ( @int9 handler ) ) ; newint9 handler . o f f s e t := @int9 handler ; newint9 handler . segment := get cs ; get pm interrupt ( kbdint , o l d i n t 9 h a n d l e r ) ; asmmovw %ds, %ax movw %ax , INT9 DS movl OLDINT9 HANDLER, % eax movl %eax , OLDHANDLER movw 4+ OLDINT9 HANDLER, % ax movw %ax , 4+OLDHANDLER end ; set pm interrupt ( kbdint , newint9 handler ) ; end ; procedure remove click ; begin set pm interrupt ( kbdint , oldint9 handler ); unlock data ( dosmemselector , s i z e o f ( dosmemselector ) ) ; unlock data ( c l i c k p r o c , s i ze o f ( c l i c k p r o c ) ) ; unlock code ( @ c l i c k e r , l o n g i n t ( @clicker dummy ) - l o n g i n t ( @ c l i c k e r ) ) ; unlock code ( @int9 handler , l o n g i n t ( @int9 dummy ) - l o n g i n t ( @int9 handler ) ) ; end ; var ch : char ; begin install click ; Writeln ( ' Enter any message . ' , ' Press r e t u r n when f i n i s h e d ' ) ; while ( ch <> #13) do begin ch := readkey ; write ( ch ) ; end ; remove click ; end . Software interrupts Ordinarily, a handler installed with set pm interrupt (86) only services software in- terrupts that are executed in protected mode; real mode software interrupts can be 58 4.2. PROTECTED MODE MEMORY ORGANIZATION redirected by set rm interrupt (88). See also set rm interrupt (88), get rm interrupt (77), set pm interrupt (86), get pm interrupt (74), lock data (82), lock code (82), enable (70), disable (67), outportb (83) Executing software interrupts Simply execute a realintr() call with the desired interrupt number and the supplied register data structure. But some of these interrupts require you to supply them a pointer to a bu er where they can store data to or obtain data from in memory. These interrupts are real mode functions and so they only can access the first Mb of linear address space, not FPC's data segment. For this reason FPC supplies a pre-initialized dos memory location within the GO32 unit. This bu er is internally used for dos func- tions too and so it's contents may change when calling other procedures. It's size can be obtained with tb size (89) and it's linear address via transfer bu er (89). An- other way is to allocate a completely new dos memory area via the global dos alloc (79) function for your use and supply its real mode address. See also: tb size (89), transfer bu er (89). global dos alloc (79), global dos free (81), realintr (84) The following examples illustrate the use of software interrupts. Program s o f t i n t ; uses go32 ; var r : t r e a l r e g s ; begin r . al := $01; r e a l i n t r ( $21 , r ) ; Writeln ( ' DOS v ' , r . al , ' . ' , r . ah , ' detected ' ) ; end . Program rmpm int ; uses cr t , go32 ; {$ASMMODE DIRECT} var r : t r e a l r e g s ; axreg : Word ; o l d i n t 2 1 h : t s e g i n f o ; newint21h : t s e g i n f o ; procedure int21h handler ; assembler ; asmcmpw $0x3001, %ax jne CallOld movw $0x3112 , % ax i r e t CallOld : ljmp %cs : OLDHANDLER OLDHANDLER: . long 0 . word 0 end ; procedure resume ; 59 4.2. PROTECTED MODE MEMORY ORGANIZATION begin Writeln ; Write ( '-- p r e s s any key to resume --' ) ; readkey ; gotoxy ( 1 , wherey ) ; c l r e o l ; end ; begin clrscr ; Writeln ( ' Executing r e a l mode i n t e r r u p t ' ) ; resume ; r . ah := $30 ; r . al := $01 ; r e a l i n t r ( $21 , r ) ; Writeln ( ' DOS v ' , r . al , ' . ' , r . ah , ' detected ' ) ; resume ; Writeln ( ' Executing p r o t e c t e d mode i n t e r r u p t ' , ' without our own handler ' ) ; Writeln ; asmmovb $0x30, %ah movb $0x01 , % al int $0x21 movw %ax , AXREG end ; Writeln ( ' DOS v ' , r . al , ' . ' , r . ah , ' detected ' ) ; resume ; Writeln ( ' As you can see the DPMI hosts ' , ' d e f a u l t p r o t e c t e d mode handler ' ) ; Writeln ( ' simply r e d i r e c t s i t to the r e a l mode handler ' ) ; resume ; Writeln ( ' Now exchanging the p r o t e c t e d mode ' , ' i n t e r r u p t with our own handler ' ) ; resume ; newint21h . o f f s e t := @int21h handler ; newint21h . segment := get cs ; get pm interrupt ( $21 , o l d i n t 2 1 h ) ; asmmovl OLDINT21H, %eax movl %eax , OLDHANDLER movw 4+ OLDINT21H, % ax movw %ax , 4+OLDHANDLER end ; set pm interrupt ( $21 , newint21h ) ; Writeln ( ' Executing r e a l mode i n t e r r u p t again ' ) ; resume ; r . ah := $30 ; r . al := $01 ; r e a l i n t r ( $21 , r ) ; Writeln ( ' DOS v ' , r . al , ' . ' , r . ah , ' detected ' ) ; Writeln ; Writeln ( ' See , i t didn ' ' t change in any way . ' ) ; resume ; Writeln ( ' Now c a l l i n g p r o t e c t e d mode i n t e r r u p t ' ) ; resume ; asmmovb $0x30, %ah 60 4.2. PROTECTED MODE MEMORY ORGANIZATION movb $0x01 , % al int $0x21 movw %ax , AXREG end ; Writeln ( ' DOS v ' , lo ( axreg ) , ' . ' , hi ( axreg ) , ' detected ' ) ; Writeln ; Writeln ( ' Now you can see that there ' ' s ' , ' a d i s t i n c t i o n between the two ways of ' ) ; Writeln ( ' c a l l i n g i n t e r r u p t s . . . ' ) ; set pm interrupt ( $21 , o l d i n t 2 1 h ) ; end . Real mode callbacks The callback mechanism can be thought of as the converse of calling a real mode procedure (i.e. interrupt), which allows your program to pass information to a real mode program, or obtain services from it in a manner that's transparent to the real mode program. In order to make a real mode callback available, you must first get the real mode callback address of your procedure and the selector and o set of a register data structure. This real mode callback address (this is a segment:o set address) can be passed to a real mode program via a software interrupt, a dos memory block or any other convenient mechanism. When the real mode program calls the callback (via a far call), the DPMI host saves the registers contents in the supplied register data structure, switches into protected mode, and enters the callback routine with the following conditions: * interrupts disabled * %CS:%EIP = 48 bit pointer specified in the original call to get rm callback (74) * %DS:%ESI = 48 bit pointer to to real mode SS:SP * %ES:%EDI = 48 bit pointer of real mode register data structure. * %SS:%ESP = locked protected mode stack * All other registers undefined The callback procedure can then extract its parameters from the real mode regis- ter data structure and/or copy parameters from the real mode stack to the pro- tected mode stack. Recall that the segment register fields of the real mode register data structure contain segment or paragraph addresses that are not valid in pro- tected mode. Far pointers passed in the real mode register data structure must be translated to virtual addresses before they can be used with a protected mode program. The callback procedure exits by executing an IRET with the address of the real mode register data structure in %ES:%EDI, passing information back to the real mode caller by modifying the contents of the real mode register data structure and/or manipulating the contents of the real mode stack. The callback procedure is responsible for setting the proper address for resumption of real mode execution into the real mode register data structure; typically, this is accomplished by extracting the return address from the real mode stack and placing it into the %CS:%EIP fields of the real mode register data structure. After the IRET, the DPMI host switches the CPU back into real mode, loads ALL registers with the contents of the real mode register data structure, and finally returns control to the real mode program. 61 4.3. TYPES, VARIABLES AND CONSTANTS All variables and code touched by the callback procedure MUST be locked to pre- vent page faults. See also: get rm callback (74), free rm callback (71), lock code (82), lock data (82) 4.3 Types, Variables and Constants Constants Constants returned by get run mode Tells you under what memory environment (e.g. memory manager) the program currently runs. rm_unknown = 0; { unknown } rm_raw = 1; { raw (without HIMEM) } rm_xms = 2; { XMS (for example with HIMEM, without EMM386) } rm_vcpi = 3; { VCPI (for example HIMEM and EMM386) } rm_dpmi = 4; { DPMI (for example \dos box or 386Max) } Note: GO32V2 always creates DPMI programs, so you need a suitable DPMI host like CWSDPMI.EXE or a Windows dos box. So you don't need to check it, these constants are only useful in GO32V1 mode. Processor flags constants They are provided for a simple check with the flags identifier in the trealregs type. To check a single flag, simply do an AND operation with the flag you want to check. It's set if the result is the same as the flag value. const carryflag = $001; parityflag = $004; auxcarryflag = $010; zeroflag = $040; signflag = $080; trapflag = $100; interruptflag = $200; directionflag = $400; overflowflag = $800; Predefined types type tmeminfo = record available_memory : Longint; available_pages : Longint; available_lockable_pages : Longint; linear_space : Longint; unlocked_pages : Longint; available_physical_pages : Longint; total_physical_pages : Longint; free_linear_space : Longint; max_pages_in_paging_file : Longint; reserved : array[0..2] of Longint; end; 62 4.3. TYPES, VARIABLES AND CONSTANTS Table 4.1: Record description Record entry Description available memory Largest available free block in bytes. available pages Maximum unlocked page allocation in pages available lockable pages Maximum locked page allocation in pages. linear space Linear address space size in pages. unlocked pages Total number of unlocked pages. available physical pages Total number of free pages. total physical pages Total number of physical pages. free linear space Free linear address space in pages. max pages in paging file Size of paging file/partition in pages. Holds information about the memory allocation, etc. NOTE: The value of a field is -1 (0 h) if the value is unknown, it's only guaranteed, that available memory contains a valid value. The size of the pages can be determined by the get page size() function. type trealregs = record case Integer of 1: { 32-bit } (EDI, ESI, EBP, Res, EBX, EDX, ECX, EAX: Longint; Flags, ES, DS, FS, GS, IP, CS, SP, SS: Word); 2: { 16-bit } (DI, DI2, SI, SI2, BP, BP2, R1, R2: Word; BX, BX2, DX, DX2, CX, CX2, AX, AX2: Word); 3: { 8-bit } (stuff: array[1..4] of Longint; BL, BH, BL2, BH2, DL, DH, DL2, DH2, CL, CH, CL2, CH2, AL, AH, AL2, AH2: Byte); 4: { Compat } (RealEDI, RealESI, RealEBP, RealRES, RealEBX, RealEDX, RealECX, RealEAX: Longint; RealFlags, RealES, RealDS, RealFS, RealGS, RealIP, RealCS, RealSP, RealSS: Word); end; registers = trealregs; These two types contain the data structure to pass register values to a interrupt handler or real mode callback. type tseginfo = record offset : Pointer; segment : Word; end; This record is used to store a full 48-bit pointer. This may be either a protected mode selector:o set address or in real mode a segment:o set address, depending on application. See also: Selectors and descriptors, dos memory access, Interrupt redirection 63 4.4. FUNCTIONS AND PROCEDURES Variables. var dosmemselector : Word; Selector to the dos memory. The whole dos memory is automatically mapped to this single descriptor at startup. This selector is the recommened way to access dos memory. var int31error : Word; This variable holds the result of a DPMI interrupt call. Any nonzero value must be treated as a critical failure. 4.4 Functions and Procedures allocate ldt descriptors Declaration: Function allocate ldt descriptors (count : Word) : Word; Description: Allocates a number of new descriptors. Parameters: count: specifies the number of requested unique descriptors. Return value: The base selector. Notes: The descriptors allocated must be initial- ized by the application with other function calls. This function returns descriptors with a limit and size value set to zero. If more than one descriptor was requested, the function returns a base selector referencing the first of a contiguous array of descriptors. The selector values for subsequent descriptors in the array can be calculated by adding the value returned by the get next selector increment value (73) function. Errors: Check the int31error variable. See also: free ldt descriptor (70), get next selector increment value (73), segment to descriptor (85), create code segment alias descriptor (67), set segment limit (88), set segment base address (88) Program sel des ; uses c rt , go32 ; const maxx = 80; maxy = 25; b y t e s p e r c e l l = 2; s c r e e n s i z e = maxx maxy b y t e s p e r c e l l ; linB8000 = $B800 1 6 ; type s t r i n g 8 0 = st r in g [ 8 0 ] ; var text save : array [0.. screensize -1] of byte ; text oldx , text oldy : Word ; 64 4.4. FUNCTIONS AND PROCEDURES t e x t s e l : Word ; procedure s t a t u s ( s : s t r i n g 8 0 ) ; begin gotoxy ( 1 , 1 ) ; c l r e o l ; write ( s ) ; readkey ; end ; procedure s e l i n f o ( s e l : Word ) ; begin gotoxy ( 1 , 2 4 ) ; c l r e o l ; writeln ( ' D e s c r i p t o r base address : $ ' , h e x s t r ( get segment base address ( s e l ) , 8 ) ) ; c l r e o l ; write ( ' D e s c r i p t o r l i m i t : ' , get segment limit ( s e l ) ) ; end ; function makechar ( ch : char ; c o l o r : byte ) : Word ; begin result := byte (ch) or ( color shl 8); end ; begin seg move ( dosmemselector , linB8000 , get ds , l o n g i n t ( @text save ) , s c r e e n s i z e ) ; text oldx := wherex ; text oldy := wherey ; s e g f i l l w o r d ( dosmemselector , linB8000 , s c r e e n s i z e div 2 , makechar ( ' ' , Black or ( Black shl 4 ) ) ) ; s t a t u s ( ' Creating s e l e c t o r ' + ' ' ' t e x t s e l ' ' to a part of text screen memory ' ) ; t e x t s e l := a l l o c a t e l d t d e s c r i p t o r s ( 1 ) ; set segment base address ( t e x t s e l , linB8000 + b y t e s p e r c e l l maxx 1 ) ; set segment limit ( t e x t s e l , s c r e e n s i z e -1-b y t e s p e r c e l l maxx 3); s e l i n f o ( t e x t s e l ) ; s t a t u s ( ' and c l e a r i n g e n t i r e memory ' + ' s e l e c t e d by ' ' t e x t s e l ' ' d e s c r i p t o r ' ) ; s e g f i l l w o r d ( t e x t s e l , 0 , ( get segment limit ( t e x t s e l )+1) div 2 , makechar ( ' ' , LightBlue shl 4 ) ) ; s t a t u s ( ' Notice that only the memory d e s c r i b e d ' + ' by the d e s c r i p t o r changed , nothing e l s e ' ) ; s t a t u s ( ' Now reducing i t ' ' s l i m i t and base and ' + ' s e t t i n g i t ' ' s d e s c r i b e d memory ' ) ; set segment base address ( t e x t s e l , 65 4.4. FUNCTIONS AND PROCEDURES get segment base address ( t e x t s e l ) + b y t e s p e r c e l l maxx ) ; set segment limit ( t e x t s e l , get segment limit ( t e x t s e l ) - b y t e s p e r c e l l maxx 2 ) ; s e l i n f o ( t e x t s e l ) ; s t a t u s ( ' Notice that the base addr i n c r e a s e d by ' + ' one l i n e but the l i m i t decreased by 2 l i n e s ' ) ; s t a t u s ( ' This should give you the hint that the ' + ' l i m i t i s r e l a t i v e to the base ' ) ; s e g f i l l w o r d ( t e x t s e l , 0 , ( get segment limit ( t e x t s e l )+1) div 2 , makechar (#176, LightMagenta or Brown shl 4 ) ) ; s t a t u s ( ' Now l e t ' ' s get crazy and copy 10 l i n e s ' + ' of data from the p r e v i o u s l y saved screen ' ) ; seg move ( get ds , l o n g i n t ( @text save ) , t e x t s e l , maxx b y t e s p e r c e l l 2 , maxx b y t e s p e r c e l l 1 0 ) ; s t a t u s ( ' At l a s t f r e e i n g the d e s c r i p t o r and ' + ' r e s t o r i n g the old screen contents . . ' ) ; s t a t u s ( ' I hope t h i s l i t t l e program may give ' + ' you some h i n t s on working with d e s c r i p t o r s ' ) ; f r e e l d t d e s c r i p t o r ( t e x t s e l ) ; seg move ( get ds , l o n g i n t ( @text save ) , dosmemselector , linB8000 , s c r e e n s i z e ) ; gotoxy ( text oldx , text oldy ) ; end . allocate memory block Declaration: Function allocate memory block (size:Longint) : Longint; Description: Allocates a block of linear memory. Parameters: size: Size of requested linear memory block in bytes. Returned values: blockhandle - the memory handle to this memory block. Linear address of the requested memory. Notes: WARNING: According to my DPMI docs this function is not implemented correctly. Normally you should also get a blockhandle to this block after successful operation. This handle is used to free the memory block afterwards or use this handle for other purposes. So this block can't be deallocated and is henceforth unusuable ! This function doesn't allocate any descriptors for this block, it's the applications resposibility to allocate and initialize for accessing this memory. Errors: Check the int31error variable. See also: free memory block (71) copyfromdos Declaration: Procedure copyfromdos (var addr; len : Longint); 66 4.4. FUNCTIONS AND PROCEDURES Description: Copies data from the pre-allocated dos memory transfer bu er to the heap. Pa- rameters: addr: data to copy to. len: number of bytes to copy to heap. Notes: Can only be used in conjunction with the dos memory transfer bu er. Errors: Check the int31error variable. See also: tb size (89), transfer bu er (89), copytodos (67) copytodos Declaration: Procedure copytodos (var addr; len : Longint); Description: Copies data from heap to the pre-allocated dos memory bu er. Parameters: addr: data to copy from. len: number of bytes to copy to dos memory bu er. Notes: This function fails if you try to copy more bytes than the transfer bu er is in size. It can only be used in conjunction with the transfer bu er. Errors: Check the int31error variable. See also: tb size (89), transfer bu er (89), copyfromdos (66) create code segment alias descriptor Declaration: Function create code segment alias descriptor (seg : Word) : Word; Description: Creates a new descriptor that has the same base and limit as the specified descrip- tor. Parameters: seg: selector. Return values: The data selector (alias). Notes: In e ect, the function returns a copy of the descriptor. The descriptor alias returned by this function will not track changes to the original descriptor. In other words, if an alias is created with this function, and the base or limit of the original segment is then changed, the two descriptors will no longer map the same memory. Errors: Check the int31error variable. See also: allocate ldt descriptors (64), set segment limit (88), set segment base address (88) disable Declaration: Procedure disable ; Description: Disables all hardware interrupts by execution a CLI instruction. Parameters: None. Errors: None. See also: enable (70) 67 4.4. FUNCTIONS AND PROCEDURES dosmemfillchar Declaration: Procedure dosmemfillchar (seg, ofs : Word; count : Longint; c : char); Description: Sets a region of dos memory to a specific byte value. Parameters: seg: real mode segment. ofs: real mode o set. count: number of bytes to set. c: value to set memory to. Notes: No range check is performed. Errors: None. See also: dosmemput (70), dosmemget (69), dosmemmove (69)dosmemmove, dosmemfillword (69), seg move (86), seg fillchar (84), seg fillword (85) Program textmess ; uses c r t , go32 ; const columns = 80; rows = 25; s c r e e n s i z e = rows columns 2; text = ' ! Hello world ! ' ; var t e x t o f s : Longint ; save screen : array [ 0 . . s c r e e n s i z e -1] of byte ; curx , cury : I n t e g e r ; begin randomize; dosmemget ( $B800 , 0 , save screen , s c r e e n s i z e ) ; curx := wherex ; cury := wherey ; gotoxy ( 1 , 1 ) ; Write ( text ) ; t e x t o f s := s c r e e n s i z e + length ( text ) 2; dosmemmove ( $B800 , 0 , $B800 , t e x t o f s , length ( text ) 2 ) ; d o s m e m f i l l c h a r ( $B800 , 0 , s c r e e n s i z e , #0); while ( not keypressed ) do begin d o s m e m f i l l c h a r ( $B800 , t e x t o f s + random( length ( text )) 2 + 1, 1 , char ( random ( 2 5 5 ) ) ) ; dosmemmove ( $B800 , t e x t o f s , $B800 , random( columns ) 2+random( rows ) columns 2, length ( text ) 2 ) ; delay ( 1 ) ; end ; readkey ; readkey ; dosmemput ( $B800 , 0 , save screen , s c r e e n s i z e ) ; gotoxy ( curx , cury ) ; end . 68 4.4. FUNCTIONS AND PROCEDURES dosmemfillword Declaration: Procedure dosmemfillword (seg,ofs : Word; count : Longint; w : Word); Description: Sets a region of dos memory to a specific word value. Parameters: seg: real mode segment. ofs: real mode o set. count: number of words to set. w: value to set memory to. Notes: No range check is performed. Errors: None. See also: dosmemput (70), dosmemget (69), dosmemmove (69), dosmemfillchar (68), seg move (86), seg fillchar (84), seg fillword (85) dosmemget Declaration: Procedure dosmemget (seg : Word; ofs : Word; var data; count : Longint); Description: Copies data from the dos memory onto the heap. Parameters: seg: source real mode segment. ofs: source real mode o set. data: destination. count: number of bytes to copy. Notes: No range checking is performed. Errors: None. See also: dosmemput (70), dosmemmove (69), dosmemfillchar (68), dosmemfillword (69), seg move (86), seg fillchar (84), seg fillword (85) For an example, see global dos alloc (79). dosmemmove Declaration: Procedure dosmemmove (sseg, sofs, dseg, dofs : Word; count : Longint); Description: Copies count bytes of data between two dos real mode memory locations. Param- eters: sseg: source real mode segment. sofs: source real mode o set. dseg: destination real mode segment. dofs: destination real mode o set. count: number of bytes to copy. Notes: No range check is performed in any way. Errors: None. See also: dosmemput (70), dosmemget (69), dosmemfillchar (68), dosmemfillword (69) seg move (86), seg fillchar (84), seg fillword (85) For an example, see seg fillchar (84). 69 4.4. FUNCTIONS AND PROCEDURES dosmemput Declaration: Procedure dosmemput (seg : Word; ofs : Word; var data; count : Longint); Description: Copies heap data to dos real mode memory. Parameters: seg: destination real mode segment. ofs: destination real mode o set. data: source. count: number of bytes to copy. Notes: No range checking is performed. Errors: None. See also: dosmemget (69), dosmemmove (69), dosmemfillchar (68), dosmemfillword (69), seg move (86), seg fillchar (84), seg fillword (85) For an example, see global dos alloc (79). enable Declaration: Procedure enable ; Description: Enables all hardware interrupts by executing a STI instruction. Parameters: None. Errors: None. See also: disable (67) free ldt descriptor Declaration: Function free ldt descriptor (des : Word) : boolean; Description: Frees a previously allocated descriptor. Parameters: des: The descriptor to be freed. Return value: True if successful, False otherwise. Notes: After this call this selector is invalid and must not be used for any memory operations anymore. Each descriptor allocated with allocate ldt descriptors (64) must be freed individually with this function, even if it was previously allocated as a part of a contiguous array of descriptors. Errors: Check the int31error variable. See also: allocate ldt descriptors (64), get next selector increment value (73) For an example, see allocate ldt descriptors (64). 70 4.4. FUNCTIONS AND PROCEDURES free memory block Declaration: Function free memory block (blockhandle : Longint) : boolean; Description: Frees a previously allocated memory block. Parameters: blockhandle: the handle to the memory area to free. Return value: True if successful, false otherwise. Notes: Frees memory that was previously allocated with allocate memory block (66) . This function doesn't free any descriptors mapped to this block, it's the application's responsibility. Errors: Check int31error variable. See also: allocate memory block (66) free rm callback Declaration: Function free rm callback (var intaddr : tseginfo) : boolean; Description: Releases a real mode callback address that was previously allocated with the get rm callback (74) function. Parameters: intaddr: real mode address bu er returned by get rm callback (74) . Return values: True if successful, False if not Errors: Check the int31error variable. See also: set rm interrupt (88), get rm callback (74) For an example, see get rm callback (74). get cs Declaration: Function get cs : Word; Description: Returns the cs selector. Parameters: None. Return values: The content of the cs segment register. Errors: None. See also: get ds (72), get ss (79) For an example, see set pm interrupt (86). get descriptor access rights Declaration: Function get descriptor access rights (d : Word) : Longint; Description: Gets the access rights of a descriptor. Parameters: d selector to descriptor. Return value: Access rights bit field. Errors: Check the int31error variable. See also: set descriptor access rights (86) 71 4.4. FUNCTIONS AND PROCEDURES get ds Declaration: Function get ds : Word; Description: Returns the ds selector. Parameters: None. Return values: The content of the ds segment register. Errors: None. See also: get cs (71), get ss (79) get linear addr Declaration: Function get linear addr (phys addr : Longint; size : Longint) : Longint; Description: Converts a physical address into a linear address. Parameters: phys addr: physical address of device. size: Size of region to map in bytes. Return value: Linear address that can be used to access the physical memory. Notes: It's the applications resposibility to allocate and set up a descriptor for access to the memory. This function shouldn't be used to map real mode addresses. Errors: Check the int31error variable. See also: allocate ldt descriptors (64), set segment limit (88), set segment base address (88) get meminfo Declaration: Function get meminfo (var meminfo : tmeminfo) : boolean; Description: Returns information about the amount of available physical memory, linear address space, and disk space for page swapping. Parameters: meminfo: bu er to fill memory information into. Return values: Due to an implementation bug this function always returns False, but it always succeeds. Notes: Only the first field of the returned structure is guaranteed to contain a valid value. Any fields that are not supported by the DPMI host will be set by the host to -1 (0FFFFFFFFH) to indicate that the information is not available. The size of the pages used by the DPMI host can be obtained with the get page size (74) function. Errors: Check the int31error variable. See also: get page size (74) Program meminf ; uses go32 ; var meminfo : tmeminfo ; begin get meminfo ( meminfo ) ; i f ( i n t 3 1 e r r o r <> 0) then 72 4.4. FUNCTIONS AND PROCEDURES begin Writeln ( ' Error g e t t i n g DPMI memory i n f o r m a t i o n . . . Halting ' ) ; Writeln ( ' DPMI e r r o r number : ' , i n t 3 1 e r r o r ) ; end else with meminfo do begin Writeln ( ' Largest a v a i l a b l e f r e e block : ' , available memory div 1 0 2 4 , ' kbytes ' ) ; i f ( a v a i l a b l e p a g e s <> -1) then Writeln ( ' Maximum a v a i l a b l e unlocked pages : ' , a v a i l a b l e p a g e s ) ; i f ( a v a i l a b l e l o c k a b l e p a g e s <> -1) then Writeln ( ' Maximum l o c k a b l e a v a i l a b l e pages : ' , a v a i l a b l e l o c k a b l e p a g e s ) ; i f ( l i n e a r s p a c e <> -1) then Writeln ( ' Li near address space s i z e : ' , l i n e a r s p a c e get page size div 1024, ' kbytes ' ) ; i f ( unlocked pages <> -1) then Writeln ( ' Total number of unlocked pages : ' , unlocked pages ) ; i f ( a v a i l a b l e p h y s i c a l p a g e s <> -1) then Writeln ( ' Total number of f r e e pages : ' , a v a i l a b l e p h y s i c a l p a g e s ) ; i f ( t o t a l p h y s i c a l p a g e s <> -1) then Writeln ( ' Total number of p h y s i c a l pages : ' , t o t a l p h y s i c a l p a g e s ) ; i f ( f r e e l i n e a r s p a c e <> -1) then Writeln ( ' Free l i n e a r address space : ' , f r e e l i n e a r s p a c e get page size div 1024, ' kbytes ' ) ; i f ( max pages in paging file <> -1) then Writeln ( ' Maximum s i z e of paging f i l e : ' , max pages in paging file get page size div 1024, ' kbytes ' ) ; end ; end . get next selector increment value Declaration: Function get next selector increment value : Word; Description: Returns the selector increment value when allocating multiple subsequent descrip- tors via allocate ldt descriptors (64). Parameters: None. Return value: Selector increment value. Notes: Because allocate ldt descriptors (64) only returns the se- lector for the first descriptor and so the value returned by this function can be used to calculate the selectors for subsequent descriptors in the array. Errors: Check the int31error variable. See also: allocate ldt descriptors (64), free ldt descriptor (70) 73 4.4. FUNCTIONS AND PROCEDURES get page size Declaration: Function get page size : Longint; Description: Returns the size of a single memory page. Return value: Size of a single page in bytes. Notes: The returned size is typically 4096 bytes. Errors: Check the int31error variable. See also: get meminfo (72) For an example, see get meminfo (72). get pm interrupt Declaration: Function get pm interrupt (vector : byte; var intaddr : tseginfo) : boolean; Description: Returns the address of a current protected mode interrupt handler. Parameters: vector: interrupt handler number you want the address to. intaddr: bu er to store address. Return values: True if successful, False if not. Notes: The returned address is a protected mode selector:o set address. Errors: Check the int31error variable. See also: set pm interrupt (86), set rm interrupt (88), get rm interrupt (77) For an example, see set pm interrupt (86). get rm callback Declaration: Function get rm callback (pm func : pointer; const reg : trealregs; var rmcb: tseginfo) : boolean; Description: Returns a unique real mode segment:offset address, known as a "real mode callback," that will transfer control from real mode to a protected mode procedure. Parameters: pm func: pointer to the protected mode callback function. reg: supplied registers structure. rmcb: bu er to real mode address of callback function. Return values: True if successful, otherwise False. Notes: Callback addresses obtained with this function can be passed by a protected mode program for example to an interrupt handler, device driver, or TSR, so that the real mode program can call procedures within the protected mode program or notify the protected mode program of an event. The contents of the supplied regs structure is not valid after function call, but only at the time of the actual callback. Errors: Check the int31error variable. See also: free rm callback (71) 74 4.4. FUNCTIONS AND PROCEDURES Program c a l l b a c k ; uses c r t , go32 ; const mouseint = $33 ; var mouse regs : t r e a l r e g s ; mouse seginfo : t s e g i n f o ; var mouse numbuttons : l o n g i n t ; mouse action : word ; mouse x , mouse y : Word ; mouse b : Word ; u s e r p r o c i n s t a l l e d : Longbool ; u s e r p r o c l en g th : Longint ; userproc proc : p o i n t e r ; {$ASMMODE DIRECT} procedure c a l l b a c k h a n d l e r ; assembler ; asmpushw %es pushw %ds pushl % edi pushl % e s i cmpl $1 , USERPROC INSTALLED je . LNoCallback pushal movw %es , % ax movw %ax , % ds movw U GO32 DOSMEMSELECTOR, % ax movw %ax , % fs c a l l USERPROC PROC popal . LNoCallback : popl % e s i popl % edi popw %ds popw %es movl (% e s i ), % eax movl %eax , % es : 42(% edi ) addw $4 , % es : 46(% edi ) i r e t end ; procedure mouse dummy ; begin end ; procedure t e x t u s e r p r o c ; begin mouse b := mouse regs . bx; 75 4.4. FUNCTIONS AND PROCEDURES mouse x := ( mouse regs . cx shr 3 ) + 1 ; mouse y := ( mouse regs . dx shr 3 ) + 1 ; end ; procedure i n s t a l l m o u s e ( u s e r p r o c : p o i n t e r ; u s e r p r o c l e n : l o n g i n t ) ; var r : t r e a l r e g s ; begin r . eax := $0; realintr (mouseint , r ); i f ( r . eax <> $FFFF ) then begin Writeln ( ' No M i r c o s o f t compatible mouse found ' ) ; Write ( ' A M i r c o s o f t compatible mouse d r i v e r i s ' ) ; writeln ( ' n e c e s s a r y to run t h i s example ' ) ; halt ; end ; i f ( r . bx = $ f f f f ) then mouse numbuttons := 2 else mouse numbuttons := r . bx ; Writeln ( mouse numbuttons , ' button M i r c o s o f t compatible mouse found . ' ) ; i f ( u s e r p r o c <> n i l ) then begin userproc proc := u s e r p r o c ; u s e r p r o c i n s t a l l e d := true ; u se r p r o c l en g th := u s e r p r o c l e n ; lock code ( userproc proc , u s er p r o c l en g t h ) ; end else begin userproc proc := n i l ; u s e r p ro c l e n g th : = 0 ; u s e r p r o c i n s t a l l e d := f a l s e ; end ; lock data ( mouse x , s i z e o f ( mouse x ) ) ; lock data ( mouse y , s i z e o f ( mouse y ) ) ; lock data ( mouse b , s i z e o f ( mouse b ) ) ; lock data ( mouse action , s i z e o f ( mouse action ) ) ; lock data ( u s e r p r o c i n s t a l l e d , s i z e o f ( u s e r p r o c i n s t a l l e d ) ) ; lock data ( @userproc proc , s i z e o f ( userproc proc ) ) ; lock data ( mouse regs , s i z e o f ( mouse regs ) ) ; lock data ( mouse seginfo , s i z e o f ( mouse seginfo ) ) ; lock code ( @callback handler , l o n g i n t ( @mouse dummy) - l o n g i n t ( @callback handler ) ) ; get rm callback ( @callback handler , mouse regs , mouse seginfo ) ; r . eax := $0c ; r . ecx := $7f ; r . edx := l o n g i n t ( mouse seginfo . o f f s e t ) ; r . es := mouse seginfo . segment ; r e a l i n t r ( mouseint , r ) ; r . eax := $01 ; r e a l i n t r ( mouseint , r ) ; end ; procedure remove mouse ; var r : t r e a l r e g s ; begin r . eax := $02 ; realintr (mouseint , r ); 76 4.4. FUNCTIONS AND PROCEDURES r . eax := $0c ; r . ecx : = 0 ; r . edx : = 0 ; r . es : = 0 ; r e a l i n t r ( mouseint , r ) ; free rm callback ( mouse seginfo ) ; i f ( u s e r p r o c i n s t a l l e d ) then begin unlock code ( userproc proc , u s e r p r oc le n gt h ) ; userproc proc := n i l ; u s e r p ro c l en g th : = 0 ; u s e r p r o c i n s t a l l e d := f a l s e ; end ; unlock data ( mouse x , s i z e o f ( mouse x ) ) ; unlock data ( mouse y , s i z e o f ( mouse y ) ) ; unlock data ( mouse b , s i z e o f ( mouse b ) ) ; unlock data ( mouse action , s i z e o f ( mouse action ) ) ; unlock data ( @userproc proc , s i ze o f ( userproc proc ) ) ; unlock data ( u s e r p r o c i n s t a l l e d , s iz e o f ( u s e r p r o c i n s t a l l e d ) ) ; unlock data ( mouse regs , s i z e o f ( mouse regs ) ) ; unlock data ( mouse seginfo , s i z e o f ( mouse seginfo ) ) ; unlock code ( @callback handler , l o n g i n t ( @mouse dummy) - l o n g i n t ( @callback handler ) ) ; f i l l c h a r ( mouse seginfo , s i z e o f ( mouse seginfo ) , 0 ) ; end ; begin install mouse ( @textuserproc , 400); Writeln ( ' Press any key to e x i t . . . ' ) ; while ( not keypressed ) do begin { w r i t e mouse s t a t e i n f o } gotoxy ( 1 , wherey ) ; write ( ' MouseX : ' , mouse x : 2 , ' MouseY : ' , mouse y : 2 , ' Buttons : ' , mouse b : 2 ) ; end ; remove mouse ; end . get rm interrupt Declaration: Function get rm interrupt (vector : byte; var intaddr : tseginfo) : boolean; Description: Returns the contents of the current machine's real mode interrupt vector for the specified interrupt. Parameters: vector: interrupt vector number. intaddr: bu er to store real mode segment:offset address. Return values: True if successful, False otherwise. Notes: The returned address is a real mode segment address, which isn't valid in protected mode. 77 4.4. FUNCTIONS AND PROCEDURES Errors: Check the int31error variable. See also: set rm interrupt (88), set pm interrupt (86), get pm interrupt (74) get run mode Declaration: Function get run mode : Word; Description: Returns the current mode your application runs with. Return values: One of the constants used by this function. Errors: None. See also: constants returned by get run mode (78) Program getrunmd ; uses go32 ; begin { depending on the detected environment , we simply w r i t e another message }case ( get run mode) of rm unknown : Writeln ( ' Unknown environment found ' ) ; rm raw : Writeln ( ' You are c u r r e n t l y running in raw mode ' , ' ( without HIMEM) ' ) ; rm xms : Writeln ( ' You are c u r r e n t l y using HIMEM. SYS only ' ) ; rm vcpi : Writeln ( ' VCPI s e r v e r detected . ' , ' You ' ' re using HIMEM and EMM386' ) ; rm dpmi : Writeln ( ' DPMI detected . ' , ' You ' ' re using a DPMI host l i k e ' , ' a windows DOS box or CWSDPMI' ) ; end ; end . get segment base address Declaration: Function get segment base address (d : Word) : Longint; Description: Returns the 32-bit linear base address from the descriptor table for the specified segment. Parameters: d: selector of the descriptor you want the base address. Return values: Linear base address of specified descriptor. Errors: Check the int31error variable. 78 4.4. FUNCTIONS AND PROCEDURES See also: allocate ldt descriptors (64), set segment base address (88), allocate ldt descriptors (64), set segment limit (88), get segment limit (79) For an example, see allocate ldt descriptors (64). get segment limit Declaration: Function get segment limit (d : Word) : Longint; Description: Returns a descriptors segment limit. Parameters: d: selector. Return value: Limit of the descriptor in bytes. Errors: Returns zero if descriptor is invalid. See also: allocate ldt descriptors (64), set segment limit (88), set segment base address (88), get segment base address (78), get ss Declaration: Function get ss : Word; Description: Returns the ss selector. Parameters: None. Return values: The content of the ss segment register. Errors: None. See also: get ds (72), get cs (71) global dos alloc Declaration: Function global dos alloc (bytes : Longint) : Longint; Description: Allocates a block of dos real mode memory. Parameters: bytes: size of requested real mode memory. Return values: The low word of the returned value contains the selector to the allocated dos memory block, the high word the corresponding real mode segment value. The o set value is always zero. This function allocates memory from dos memory pool, i.e. memory below the 1 MB boundary that is controlled by dos. Such memory blocks are typically used to exchange data with real mode programs, TSRs, or device drivers. The function returns both the real mode segment base address of the block and one descriptor that can be used by protected mode appli- cations to access the block. This function should only used for temporary bu ers to get real mode information (e.g. interrupts that need a data structure in ES:(E)DI), because every single block needs an unique selector. The returned selector should only be freed by a global dos free (81) call. Errors: Check the int31error variable. See also: global dos free (81) 79 4.4. FUNCTIONS AND PROCEDURES Program b u f f e r ; uses go32 ; procedure d o s a l l o c ( var s e l e c t o r : word ; var segment : word ; s i z e : l o n g i n t ) ; var res : l o n g i n t ; begin res := global dos alloc ( size ); s e l e c t o r := word ( res ) ; segment := word ( res shr 1 6 ) ; end ; procedure d o s f r e e ( s e l e c t o r : word ) ; begin global dos free ( selector ); end ; type VBEInfoBuf = record S i g n a t u r e : array [ 0 . . 3 ] of char ; Version : Word ; r e s e r v e d : array [ 0 . . 5 0 5 ] of byte ; end ; var s e l e c t o r , segment : Word ; r : t r e a l r e g s ; i n f o b u f : VBEInfoBuf ; begin fillchar (r , sizeof (r ), 0); f i l l c h a r ( i n f o b u f , s i z e o f ( VBEInfoBuf ) , 0 ) ; d o s a l l o c ( s e l e c t o r , segment , s i ze o f ( VBEInfoBuf ) ) ; i f ( i n t 3 1 e r r o r <>0) then begin Writeln ( ' Error while a l l o c a t i n g r e a l mode memory , h a l t i n g ' ) ; halt ; end ; i n f o b u f . S i g n a t u r e := ' VBE2' ; dosmemput ( segment , 0 , i n f o b u f , s i z e o f ( i n f o b u f ) ) ; r . ax := $4f00 ; r . es := segment ; r e a l i n t r ( $10 , r ) ; dosmemget ( segment , 0 , i n f o b u f , s i z e o f ( i n f o b u f ) ) ; d o s f r e e ( s e l e c t o r ) ; i f ( r . ax <> $4f ) then begin Writeln ( ' VBE BIOS e x t e n s i o n not a v a i l a b l e , f u n c t i o n c a l l f a i l e d ' ) ; halt ; end ; i f ( i n f o b u f . s i g n a t u r e [ 0 ] = ' V' ) and ( i n f o b u f . s i g n a t u r e [ 1 ] = ' E' ) and ( i n f o b u f . s i g n a t u r e [ 2 ] = ' S ' ) and ( i n f o b u f . s i g n a t u r e [ 3 ] = ' A' ) then begin Writeln ( ' VBE v e r s i o n ' , hi ( i n f o b u f . v e r s i o n ) , ' . ' , lo ( i n f o b u f . v e r s i o n ) , ' detected ' ) ; end ; end . 80 4.4. FUNCTIONS AND PROCEDURES global dos free Declaration: Function global dos free (selector :Word) : boolean; Description: Frees a previously allocated dos memory block. Parameters: selector: selector to the dos memory block. Return value: True if successful, False otherwise. Notes: The descriptor allocated for the memory block is automatically freed and hence invalid for further use. This function should only be used for memory allocated by global dos alloc (79). Errors: Check the int31error variable. See also: global dos alloc (79) For an example, see global dos alloc (79). inportb Declaration: Function inportb (port : Word) : byte; Description: Reads 1 byte from the selected I/O port. Parameters: port: the I/O port number which is read. Return values: Current I/O port value. Errors: None. See also: outportb (83), inportw (81), inportl (81) inportl Declaration: Function inportl (port : Word) : Longint; Description: Reads 1 longint from the selected I/O port. Parameters: port: the I/O port number which is read. Return values: Current I/O port value. Errors: None. See also: outportb (83), inportb (81), inportw (81) inportw Declaration: Function inportw (port : Word) : Word; Description: Reads 1 word from the selected I/O port. Parameters: port: the I/O port number which is read. Return values: Current I/O port value. Errors: None. See also: outportw (83) inportb (81), inportl (81) 81 4.4. FUNCTIONS AND PROCEDURES lock code Declaration: Function lock code (functionaddr : pointer; size : Longint) : boolean; Description: Locks a memory range which is in the code segment selector. Parameters: functionaddr: address of the function to be locked. size: size in bytes to be locked. Return values: True if successful, False otherwise. Errors: Check the int31error variable. See also: lock linear region (82), lock data (82), unlock linear region (90), unlock data (89), unlock code (89) For an example, see get rm callback (74). lock data Declaration: Function lock data (var data; size : Longint) : boolean; Description: Locks a memory range which resides in the data segment selector. Parameters: data: address of data to be locked. size: length of data to be locked. Return values: True if successful, False otherwise. Errors: Check the int31error variable. See also: lock linear region (82), lock code (82), unlock linear region (90), unlock data (89), unlock code (89) For an example, see get rm callback (74). lock linear region Declaration: Function lock linear region (linearaddr, size : Longint) : boolean; Description: Locks a memory region to prevent swapping of it. Parameters: linearaddr: the linear address of the memory are to be locked. size: size in bytes to be locked. Return value: True if successful, False otherwise. Errors: Check the int31error variable. See also: lock data (82), lock code (82), unlock linear region (90), unlock data (89), un- lock code (89) 82 4.4. FUNCTIONS AND PROCEDURES outportb Declaration: Procedure outportb (port : Word; data : byte); Description: Sends 1 byte of data to the specified I/O port. Parameters: port: the I/O port number to send data to. data: value sent to I/O port. Return values: None. Errors: None. See also: inportb (81), outportl (83), outportw (83) program outport ; uses c r t , go32 ; begin { turn on speaker } outportb ( $61 , $ f f ) ; { wait a l i t t l e b i t } delay ( 5 0 ) ; { turn i t o f f again } outportb ( $61 , $0 ) ; end . outportl Declaration: Procedure outportl (port : Word; data : Longint); Description: Sends 1 longint of data to the specified I/O port. Parameters: port: the I/O port number to send data to. data: value sent to I/O port. Return values: None. Errors: None. See also: inportl (81), outportw (83), outportb (83) For an example, see outportb (83). outportw Declaration: Procedure outportw (port : Word; data : Word); Description: Sends 1 word of data to the specified I/O port. Parameters: port: the I/O port number to send data to. data: value sent to I/O port. Return values: None. Errors: None. See also: inportw (81), outportl (83), outportb (83) For an example, see outportb (83). 83 4.4. FUNCTIONS AND PROCEDURES realintr Declaration: Function realintr (intnr: Word; var regs : trealregs) : boolean; Description: Simulates an interrupt in real mode. Parameters: intnr: interrupt number to issue in real mode. regs: registers data structure. Return values: The supplied registers data structure contains the values that were returned by the real mode interrupt. True if successful, False if not. Notes: The function transfers control to the address specified by the real mode interrupt vector of intnr. The real mode handler must return by executing an IRET. Errors: Check the int31error variable. See also: Program f l a g s ; uses go32 ; var r : t r e a l r e g s ; begin r . ax := $5300; r . bx : = 0 ; r e a l i n t r ( $15 , r ) ; { check i f c a r r y c l e a r and w r i t e a s u i t e d message } i f ( ( r . f l a g s and c a r r y f l a g )=0) then begin Writeln ( ' APM v ' , ( r . ah and $f ) , ' . ' , ( r . al shr 4 ) , ( r . al and $f ) , ' detected ' ) ; end else Writeln ( ' APM not p r e s e n t ' ) ; end . seg fillchar Declaration: Procedure seg fillchar (seg : Word; ofs : Longint; count : Longint; c : char); Description: Sets a memory area to a specific value. Parameters: seg: selector to memory area. ofs: o set to memory. count: number of bytes to set. c: byte data which is set. Return values: None. Notes: No range check is done in any way. Errors: None. See also: seg move (86), seg fillword (85), dosmemfillchar (68), dosmemfillword (69), dos- memget (69), dosmemput (70), dosmemmove (69) 84 4.4. FUNCTIONS AND PROCEDURES Program s v g a s e l ; uses go32 ; var v g a s e l : Word ; r : t r e a l r e g s ; begin r . eax := $13 ; r e a l i n t r ( $10 , r ) ; v g a s e l := segment to descriptor ( $A000 ) ; { simply f i l l the screen memory with c o l o r 15 } s e g f i l l c h a r ( v g a s e l , 0 , 6 4 0 0 0 , # 1 5 ) ; readln ; { back to text mode } r . eax := $3 ; r e a l i n t r ( $10 , r ) ; end . seg fillword Declaration: Procedure seg fillword (seg : Word; ofs : Longint; count : Longint; w :Word); Description: Sets a memory area to a specific value. Parameters: seg: selector to memory area. ofs: o set to memory. count: number of words to set. w: word data which is set. Return values: None. Notes: No range check is done in any way. Errors: None. See also: seg move (86), seg fillchar (84), dosmemfillchar (68), dosmemfillword (69), dos- memget (69), dosmemput (70), dosmemmove (69) For an example, see allocate ldt descriptors (64). segment to descriptor Declaration: Function segment to descriptor (seg : Word) : Word; Description: Maps a real mode segment (paragraph) address onto an descriptor that can be used by a protected mode program to access the same memory. Parameters: seg: the real mode segment you want the descriptor to. Return values: Descriptor to real mode segment address. Notes: The returned descriptors limit will be set to 64 kB. Multiple calls to this function with the same segment address will return the same selector. Descriptors created by this function can never be modified or freed. Programs which need to examine various real mode addresses using the same selector should use the function allocate ldt descriptors (64) and change the base address as necessary. 85 4.4. FUNCTIONS AND PROCEDURES Errors: Check the int31error variable. See also: allocate ldt descriptors (64), free ldt descriptor (70), set segment base address (88) For an example, see seg fillchar (84). seg move Declaration: Procedure seg move (sseg : Word; source : Longint; dseg : Word; dest : Longint; count : Longint); Description: Copies data between two memory locations. Parameters: sseg: source selector. source: source o set. dseg: destination selector. dest: destination o set. count: size in bytes to copy. Return values: None. Notes: Overlapping is only checked if the source selector is equal to the destination selector. No range check is done. Errors: None. See also: seg fillchar (84), seg fillword (85), dosmemfillchar (68), dosmemfillword (69), dos- memget (69), dosmemput (70), dosmemmove (69) For an example, see allocate ldt descriptors (64). set descriptor access rights Declaration: Function set descriptor access rights (d : Word; w : Word) : Longint; Description: Sets the access rights of a descriptor. Parameters: d: selector. w: new descriptor access rights. Return values: This function doesn't return anything useful. Errors: Check the int31error variable. See also: get descriptor access rights (71) set pm interrupt Declaration: Function set pm interrupt (vector : byte; const intaddr : tseginfo) : boolean; Description: Sets the address of the protected mode handler for an interrupt. Parameters: vector: number of protected mode interrupt to set. intaddr: selector:o set address to the interrupt vector. 86 4.4. FUNCTIONS AND PROCEDURES Return values: True if successful, False otherwise. Notes: The address supplied must be a valid selector:offset protected mode address. Errors: Check the int31error variable. See also: get pm interrupt (74), set rm interrupt (88), get rm interrupt (77) Program int pm ; uses cr t , go32 ; const i n t 1 c = $1c ; var o l d i n t 1 c : t s e g i n f o ; newint1c : t s e g i n f o ; int1c counter : Longint ; {$ASMMODE DIRECT} procedure i n t 1 c h an d l e r ; assembler ; asm cli pushw %ds pushw %ax movw %cs : INT1C DS, % ax movw %ax , % ds i n c l INT1C COUNTER popw %ax popw %ds s t i i r e t INT1C DS : . word 0 end ; var i : Longint ; begin newint1c . offset := @int1c handler ; newint1c . segment := get cs ; get pm interrupt ( i n t 1 c , o l d i n t 1 c ) ; asmmovw %ds, %ax movw %ax , INT1C DS end ; Writeln ( '-- Press any key to e x i t --' ) ; set pm interrupt ( i n t 1 c , newint1c ) ; while ( not keypressed ) do begin gotoxy ( 1 , wherey ) ; write ( ' Number of i n t e r r u p t s occured : ' , int1c counter ) ; end ; set pm interrupt ( i n t 1 c , o l d i n t 1 c ) ; end . 87 4.4. FUNCTIONS AND PROCEDURES set rm interrupt Declaration: Function set rm interrupt (vector : byte; const intaddr : tseginfo) : boolean; Description: Sets a real mode interrupt handler. Parameters: vector: the interrupt vector number to set. intaddr: address of new interrupt vector. Return values: True if successful, otherwise False. Notes: The address supplied MUST be a real mode segment address, not a selector:offset address. So the interrupt handler must either reside in dos memory (below 1 Mb boundary) or the application must allocate a real mode callback address with get rm callback (74). Errors: Check the int31error variable. See also: get rm interrupt (77), set pm interrupt (86), get pm interrupt (74), get rm callback (74) set segment base address Declaration: Function set segment base address (d : Word; s : Longint) : boolean; Description: Sets the 32-bit linear base address of a descriptor. Parameters: d: selector. s: new base address of the descriptor. Errors: Check the int31error variable. See also: allocate ldt descriptors (64), get segment base address (78), allocate ldt descriptors (64), set segment limit (88), get segment base address (78), get segment limit (79) set segment limit Declaration: Function set segment limit (d : Word; s : Longint) : boolean; Description: Sets the limit of a descriptor. Parameters: d: selector. s: new limit of the descriptor. Return values: Returns True if successful, else False. Notes: The new limit speci- fied must be the byte length of the segment - 1. Segment limits bigger than or equal to 1MB must be page aligned, they must have the lower 12 bits set. Errors: Check the int31error variable. See also: allocate ldt descriptors (64), set segment base address (88), get segment limit (79), set segment limit (88) For an example, see allocate ldt descriptors (64). 88 4.4. FUNCTIONS AND PROCEDURES tb size Declaration: Function tb size : Longint; Description: Returns the size of the pre-allocated dos memory bu er. Parameters: None. Return values: The size of the pre-allocated dos memory bu er. Notes: This block always seems to be 16k in size, but don't rely on this. Errors: None. See also: transfer bu er (89), copyfromdos (66) copytodos (67) transfer bu er Declaration: Function transfer buffer : Longint; Description: transfer buffer returns the o set of the transfer bu er. Errors: None. See also: tb size (89) unlock code Declaration: Function unlock code (functionaddr : pointer; size : Longint) : boolean; Description: Unlocks a memory range which resides in the code segment selector. Parameters: functionaddr: address of function to be unlocked. size: size bytes to be unlocked. Return value: True if successful, False otherwise. Errors: Check the int31error variable. See also: unlock linear region (90), unlock data (89), lock linear region (82), lock data (82), lock code (82) For an example, see get rm callback (74). unlock data Declaration: Function unlock data (var data; size : Longint) : boolean; Description: Unlocks a memory range which resides in the data segment selector. Paramters: data: address of memory to be unlocked. size: size bytes to be unlocked. Return values: True if successful, False otherwise. Errors: Check the int31error variable. See also: unlock linear region (90), unlock code (89), lock linear region (82), lock data (82), lock code (82) For an example, see get rm callback (74). 89 4.4. FUNCTIONS AND PROCEDURES unlock linear region Declaration: Function unlock linear region (linearaddr, size : Longint) : boolean; Description: Unlocks a previously locked linear region range to allow it to be swapped out again if needed. Parameters: linearaddr: linear address of the memory to be unlocked. size: size bytes to be unlocked. Return values: True if successful, False otherwise. Errors: Check the int31error variable. See also: unlock data (89), unlock code (89), lock linear region (82), lock data (82), lock code (82) 90 Chapter 5 The GRAPH unit. This document describes the GRAPH unit for Free Pascal, under dos. The unit was first written for dos by Florian kl¨ampfl. This chapter is divided in three sections. * The first section gives an introduction to the graph unit. * The second section lists the pre-defined constants, types and variables. * The second section describes the functions which appear in the interface part of the GRAPH unit. 5.1 Introduction Requirements The unit Graph exports functions and procedures for graphical output. It requires at least a VESA compatible VGA-Card or a VGA-Card with software-driver (min. 512Kb video memory). Before the graph unit can be used, be sure your graphics adapter supports the VESA-Standard. Otherwise in the most cases you can try to use a VESA-TSR to make your adapter VESA compatible (e.g. UNIVBE). 5.2 Constants, Types and Variables Types ArcCoordsType = record X,Y,Xstart,Ystart,Xend,Yend : Integer; end; FillPatternType = Array [1..8] of Byte; FillSettingsType = Record Pattern,Color : Word end; LineSettingsType = Record LineStyle,Pattern, Width : Word; end; PaletteType = Record Size : Byte; Colors : array[0..MAxColor] of shortint; 91 5.3. FUNCTIONS AND PROCEDURES end; PointType = Record X,Y : Integer; end; TextSettingsType = Record Font,Direction, CharSize, Horiz, Vert : Word end; ViewPortType = Record X1,Y1,X2,Y2 : Integer; Clip : Boolean end; 5.3 Functions and procedures Arc Declaration: Procedure Arc (X,Y : Integer; start,stop, radius : Word); Description: Arc draws part of a circle with center at (X,Y), radius radius, starting from angle start, stopping at angle stop. These angles are measured counterclockwise. Errors: None. See also: Circle (92),Ellipse (94) GetArcCoords (94),PieSlice (102), Sector (103) Bar Declaration: Procedure Bar (X1,Y1,X2,Y2 : Integer); Description: Draws a rectangle with corners at (X1,Y1) and (X2,Y2) and fills it with the current color and fill-style. Errors: None. See also: Bar3D (92), Rectangle (103) Bar3D Declaration: Procedure Bar3D (X1,Y1,X2,Y2 : Integer; depth : Word; Top : Boolean); Description: Draws a 3-dimensional Bar with corners at (X1,Y1) and (X2,Y2) and fills it with the current color and fill-style. Depth specifies the number of pixels used to show the depth of the bar. If Top is true; then a 3-dimensional top is drawn. Errors: None. See also: Bar (92), Rectangle (103) Circle Declaration: Procedure Circle (X,Y : Integer; Radius : Word); Description: Circle draws part of a circle with center at (X,Y), radius radius. Errors: None. See also: Ellipse (94),Arc (92) GetArcCoords (94),PieSlice (102), Sector (103) 92 5.3. FUNCTIONS AND PROCEDURES ClearDevice Declaration: Procedure ClearDevice ; Description: Clears the graphical screen (with the current background color), and sets the pointer at (0,0) Errors: None. See also: ClearViewPort (93), SetBkColor (104) ClearViewPort Declaration: Procedure ClearViewPort ; Description: Clears the current view-port. The current background color is used as filling color. The pointer is set at (0,0) Errors: None. See also: ClearDevice (93),SetViewPort (107), SetBkColor (104) CloseGraph Declaration: Procedure CloseGraph ; Description: Closes the graphical system, and restores the screen modus which was active before the graphical modus was activated. Errors: None. See also: InitGraph (100) DetectGraph Declaration: Procedure DetectGraph (Var Driver, Modus : Integer); Description: Checks the hardware in the PC and determines the driver and screen-modus to be used. These are returned in Driver and Modus, and can be fed to InitGraph. See the InitGraph for a list of drivers and modi. Errors: None. See also: InitGraph (100) DrawPoly Declaration: Procedure DrawPoly (NumberOfPoints : Word; Var PolyPoints; Description: Draws a polygone with NumberOfPoints corner points, using the current color and line-style. PolyPoints is an array of type PointType. Errors: None. See also: Bar (92), seepBar3D, Rectangle (103) 93 5.3. FUNCTIONS AND PROCEDURES Ellipse Declaration: Procedure Ellipse (X,Y : Integer; Start,Stop,XRadius,YRadius : Word); Description: Ellipse draws part of an ellipse with center at (X,Y). XRadius and Yradius are the horizontal and vertical radii of the ellipse. Start and Stop are the starting and stopping angles of the part of the ellipse. They are measured counterclockwise from the X-axis. Errors: None. See also: Arc (92) Circle (92), FillEllipse (94) FillEllipse Declaration: Procedure FillEllipse (X,Y : Integer; Xradius,YRadius: Word); Description: Ellipse draws an ellipse with center at (X,Y). XRadius and Yradius are the horizontal and vertical radii of the ellipse. The ellipse is filled with the current color and fill-style. Errors: None. See also: Arc (92) Circle (92), GetArcCoords (94),PieSlice (102), Sector (103) FillPoly Declaration: Procedure FillPoly (NumberOfPoints : Word; Var PolyPoints); Description: Draws a polygone with NumberOfPoints corner points and fills it using the current color and line-style. PolyPoints is an array of type PointType. Errors: None. See also: Bar (92), seepBar3D, Rectangle (103) FloodFill Declaration: Procedure FloodFill (X,Y : Integer; BorderColor : Word); Description: Fills the area containing the point (X,Y), bounded by the color BorderColor. Errors: None See also: SetColor (104), SetBkColor (104) GetArcCoords Declaration: Procedure GetArcCoords (Var ArcCoords : ArcCoordsType); Description: GetArcCoords returns the coordinates of the latest Arc or Ellipse call. Errors: None. See also: Arc (92), Ellipse (94) 94 5.3. FUNCTIONS AND PROCEDURES GetAspectRatio Declaration: Procedure GetAspectRatio (Var Xasp,Yasp : Word); Description: GetAspectRatio determines the e ective resolution of the screen. The aspect ration can the be calculated as Xasp/Yasp. Errors: None. See also: InitGraph (100),SetAspectRatio (104) GetBkColor Declaration: Function GetBkColor : Word; Description: GetBkColor returns the current background color (the palette entry). Errors: None. See also: GetColor (95),SetBkColor (104) GetColor Declaration: Function GetColor : Word; Description: GetColor returns the current drawing color (the palette entry). Errors: None. See also: GetColor (95),SetBkColor (104) GetDefaultPalette Declaration: Procedure GetDefaultPalette (Var Palette : PaletteType); Description: Returns the current palette in Palette. Errors: None. See also: GetColor (95), GetBkColor (95) GetDriverName Declaration: Function GetDriverName : String; Description: GetDriverName returns a string containing the name of the current driver. Errors: None. See also: GetModeName (97), InitGraph (100) GetFillPattern Declaration: Procedure GetFillPattern (Var FillPattern : FillPatternType); Description: GetFillPattern returns an array with the current fill-pattern in FillPattern Errors: None See also: SetFillPattern (105) 95 5.3. FUNCTIONS AND PROCEDURES GetFillSettings Declaration: Procedure GetFillSettings (Var FillInfo : FillSettingsType); Description: GetFillSettings returns the current fill-settings in FillInfo Errors: None. See also: SetFillPattern (105) GetGraphMode Declaration: Function GetGraphMode : Integer; Description: GetGraphMode returns the current graphical modus Errors: None. See also: InitGraph (100) GetImage Declaration: Procedure GetImage (X1,Y1,X2,Y2 : Integer, Var Bitmap; Description: GetImage Places a copy of the screen area (X1,Y1) to X2,Y2 in BitMap Errors: Bitmap must have enough room to contain the image. See also: ImageSize (99), PutImage (102) GetLineSettings Declaration: Procedure GetLineSettings (Var LineInfo : LineSettingsType); Description: GetLineSettings returns the current Line settings in LineInfo Errors: None. See also: SetLineStyle (106) GetMaxColor Declaration: Function GetMaxColor : Word; Description: GetMaxColor returns the maximum color-number which can be set with SetColor Errors: None. See also: SetColor (104), GetPaletteSize (97) GetMaxMode Declaration: Function GetMaxMode : Word; Description: GetMaxMode returns the highest modus for the current driver. Errors: None. See also: InitGraph (100) 96 5.3. FUNCTIONS AND PROCEDURES GetMaxX Declaration: Function GetMaxX : Word; Description: GetMaxX returns the maximum horizontal screen length Errors: None. See also: GetMaxY (97) GetMaxY Declaration: Function GetMaxY : Word; Description: GetMaxY returns the maximum number of screen lines Errors: None. See also: GetMaxY (97) GetModeName Declaration: Function GetModeName (Var modus : Integer) : String; Description: Returns a string with the name of modus Modus Errors: None. See also: GetDriverName (95), InitGraph (100) GetModeRange Declaration: Procedure GetModeRange (Driver : Integer; LoModus, HiModus: Integer); Description: GetModeRange returns the Lowest and Highest modus of the currently installed driver. Errors: None. See also: InitGraph (100) GetPalette Declaration: Procedure GetPalette (Var Palette : PaletteType); Description: GetPalette returns in Palette the current palette. Errors: None. See also: GetPaletteSize (97), SetPalette (106) GetPaletteSize Declaration: Function GetPaletteSize : Word; Description: GetPaletteSize returns the maximum number of entries in the current palette. Errors: None. See also: GetPalette (97), SetPalette (106) 97 5.3. FUNCTIONS AND PROCEDURES GetPixel Declaration: Function GetPixel (X,Y : Integer) : Word; Description: GetPixel returns the color of the point at (X,Y) Errors: None. See also: GetTextSettings Declaration: Procedure GetTextSettings (Var TextInfo : TextSettingsType); Description: GetTextSettings returns the current text style settings : The font, direction, size and placement as set with SetTextStyle and SetTextJustify Errors: None. See also: SetTextStyle (107), SetTextJustify (106) GetViewSettings Declaration: Procedure GetViewSettings (Var ViewPort : ViewPortType); Description: GetViewSettings returns the current view-port and clipping settings in ViewPort. Errors: None. See also: SetViewPort (107) GetX Declaration: Function GetX : Integer; Description: GetX returns the X-coordinate of the current position of the graphical pointer Errors: None. See also: GetY (98) GetY Declaration: Function GetY : Integer; Description: GetY returns the Y-coordinate of the current position of the graphical pointer Errors: None. See also: GetX (98) 98 5.3. FUNCTIONS AND PROCEDURES GraphDefaults Declaration: Procedure GraphDefaults ; Description: GraphDefaults resets all settings for view-port, palette, foreground and back- ground pattern, line-style and pattern, filling style, filling color and pattern, font, text-placement and text size. Errors: None. See also: SetViewPort (107), SetFillStyle (105), SetColor (104), SetBkColor (104), SetLineStyle (106) GraphErrorMsg Declaration: Function GraphErrorMsg (ErrorCode : Integer) : String; Description: GraphErrorMsg returns a string describing the error Errorcode. This string can be used to let the user know what went wrong. Errors: None. See also: GraphResult (99) GraphResult Declaration: Function GraphResult : Integer; Description: GraphResult returns an error-code for the last graphical operation. If the re- turned value is zero, all went well. A value di erent from zero means an error has occurred. Except for all operations which draw something on the screen, the following procedures also can produce a GraphResult di erent from zero: *InstallUserFont (100) *SetLineStyle (106) *SetWriteMode (108) *SetFillStyle (105) *SetTextJustify (106) *SetGraphMode (105) *SetTextStyle (107) Errors: None. See also: GraphErrorMsg (99) ImageSize Declaration: Function ImageSize (X1,Y1,X2,Y2 : Integer) : Word; Description: ImageSize returns the number of bytes needed to store the image in the rectangle defined by (X1,Y1) and (X2,Y2). Errors: None. See also: GetImage (96) 99 5.3. FUNCTIONS AND PROCEDURES InitGraph Declaration: Procedure InitGraph (var GraphDriver,GraphModus : integer; const PathToDriver : string); Description: InitGraph initializes the graph package. GraphDriver has two valid values: GraphDriver=0 which performs an auto detect and initializes the highest possible mode with the most colors. 1024x768x64K is the highest possible resolution sup- ported by the driver, if you need a higher resolution, you must edit MODES.PPI. If you need another mode, then set GraphDriver to a value di erent from zero and graphmode to the mode you wish (VESA modes where 640x480x256 is 101h etc.). PathToDriver is only needed, if you use the BGI fonts from Borland. Errors: None. See also: Introduction, (page 91), DetectGraph (93), CloseGraph (93), GraphResult (99) Example: vargd,gm : integer; PathToDriver : string; begin gd:=detect; { highest possible resolution } gm:=0; { not needed, auto detection } PathToDriver:='C:\PP\BGI'; { path to BGI fonts, drivers aren't needed } InitGraph(gd,gm,PathToDriver); if GraphResult<>grok then halt; ..... { whatever you need } CloseGraph; { restores the old graphics mode } end. InstallUserDriver Declaration: Function InstallUserDriver (DriverPath : String; AutoDetectPtr: Pointer) : Integer; Description: InstallUserDriver adds the device-driver DriverPath to the list of .BGI drivers. AutoDetectPtr is a pointer to a possible auto-detect function. Errors: None. See also: InitGraph (100), InstallUserFont (100) InstallUserFont Declaration: Function InstallUserFont (FontPath : String) : Integer; Description: InstallUserFont adds the font in FontPath to the list of fonts of the .BGI system. Errors: None. See also: InitGraph (100), InstallUserDriver (100) 100 5.3. FUNCTIONS AND PROCEDURES Line Declaration: Procedure Line (X1,Y1,X2,Y2 : Integer); Description: Line draws a line starting from (X1,Y1 to (X2,Y2), in the current line style and color. The current position is put to (X2,Y2) Errors: None. See also: LineRel (101),LineTo (101) LineRel Declaration: Procedure LineRel (DX,DY : Integer); Description: LineRel draws a line starting from the current pointer position to the point(DX,DY, relative to the current position, in the current line style and color. The Current Position is set to the endpoint of the line. Errors: None. See also: Line (101), LineTo (101) LineTo Declaration: Procedure LineTo (DX,DY : Integer); Description: LineTo draws a line starting from the current pointer position to the point(DX,DY, relative to the current position, in the current line style and color. The Current position is set to the end of the line. Errors: None. See also: LineRel (101),Line (101) MoveRel Declaration: Procedure MoveRel (DX,DY : Integer; Description: MoveRel moves the pointer to the point (DX,DY), relative to the current pointer position Errors: None. See also: MoveTo (101) MoveTo Declaration: Procedure MoveTo (X,Y : Integer; Description: MoveTo moves the pointer to the point (X,Y). Errors: None. See also: MoveRel (101) 101 5.3. FUNCTIONS AND PROCEDURES OutText Declaration: Procedure OutText (Const TextString : String); Description: OutText puts TextString on the screen, at the current pointer position, using the current font and text settings. The current position is moved to the end of the text. Errors: None. See also: OutTextXY (102) OutTextXY Declaration: Procedure OutTextXY (X,Y : Integer; Const TextString : String); Description: OutText puts TextString on the screen, at position (X,Y), using the current font and text settings. The current position is moved to the end of the text. Errors: None. See also: OutText (102) PieSlice Declaration: Procedure PieSlice (X,Y : Integer; Start,Stop,Radius : Word); Description: PieSlice draws and fills a sector of a circle with center (X,Y) and radius Radius, starting at angle Start and ending at angle Stop. Errors: None. See also: Arc (92), Circle (92), Sector (103) PutImage Declaration: Procedure PutImage (X1,Y1 : Integer; Var Bitmap; How : word) ; Description: PutImage Places the bitmap in Bitmap on the screen at (X1,Y1). How determines how the bitmap will be placed on the screen. Possible values are : *CopyPut *XORPut *ORPut *AndPut *NotPut Errors: None See also: ImageSize (99),GetImage (96) PutPixel Declaration: Procedure PutPixel (X,Y : Integer; Color : Word); Description: Puts a point at (X,Y) using color Color Errors: None. See also: GetPixel (98) 102 5.3. FUNCTIONS AND PROCEDURES Rectangle Declaration: Procedure Rectangle (X1,Y1,X2,Y2 : Integer); Description: Draws a rectangle with corners at (X1,Y1) and (X2,Y2), using the current color and style. Errors: None. See also: Bar (92), Bar3D (92) RegisterBGIDriver Declaration: Function RegisterBGIDriver (Driver : Pointer) : Integer; Description: Registers a user-defined BGI driver Errors: None. See also: InstallUserDriver (100), RegisterBGIFont (103) RegisterBGIFont Declaration: Function RegisterBGIFont (Font : Pointer) : Integer; Description: Registers a user-defined BGI driver Errors: None. See also: InstallUserFont (100), RegisterBGIDriver (103) RestoreCRTMode Declaration: Procedure RestoreCRTMode ; Description: Restores the screen modus which was active before the graphical modus was started. Errors: None. See also: InitGraph (100) Sector Declaration: Procedure Sector (X,Y : Integer; Start,Stop,XRadius,YRadius : Word); Description: Sector draws and fills a sector of an ellipse with center (X,Y) and radii XRadius and YRadius, starting at angle Start and ending at angle Stop. Errors: None. See also: Arc (92), Circle (92), PieSlice (102) 103 5.3. FUNCTIONS AND PROCEDURES SetActivePage Declaration: Procedure SetActivePage (Page : Word); Description: Sets Page as the active page for all graphical output. Errors: None. See also: SetAllPallette Declaration: Procedure SetAllPallette (Var Palette); Description: Sets the current palette to Palette. Palette is an untyped variable, usually pointing to a record of type PaletteType Errors: None. See also: GetPalette (97) SetAspectRatio Declaration: Procedure SetAspectRatio (Xasp,Yasp : Word); Description: Sets the aspect ratio of the current screen to Xasp/Yasp. Errors: None See also: InitGraph (100), GetAspectRatio (95) SetBkColor Declaration: Procedure SetBkColor (Color : Word); Description: Sets the background color to Color. Errors: None. See also: GetBkColor (95), SetColor (104) SetColor Declaration: Procedure SetColor (Color : Word); Description: Sets the foreground color to Color. Errors: None. See also: GetColor (95), SetBkColor (104) 104 5.3. FUNCTIONS AND PROCEDURES SetFillPattern Declaration: Procedure SetFillPattern (FillPattern : FillPatternType, Color : Word); Description: SetFillPattern sets the current fill-pattern to FillPattern, and the filling color to Color The pattern is an 8x8 raster, corresponding to the 64 bits in FillPattern. Errors: None See also: GetFillPattern (95), SetFillStyle (105) SetFillStyle Declaration: Procedure SetFillStyle (Pattern,Color : word); Description: SetFillStyle sets the filling pattern and color to one of the predefined filling patterns. Pattern can be one of the following predefined constants : *EmptyFill Uses backgroundcolor. *SolidFill Uses filling color *LineFill Fills with horizontal lines. *ltSlashFill Fills with lines from left-under to top-right. *SlashFill Idem as previous, thick lines. *BkSlashFill Fills with thick lines from left-Top to bottom-right. *LtBkSlashFill Idem as previous, normal lines. *HatchFill Fills with a hatch-like pattern. *XHatchFill Fills with a hatch pattern, rotated 45 degrees. *InterLeaveFill *WideDotFill Fills with dots, wide spacing. *CloseDotFill Fills with dots, narrow spacing. *UserFill Fills with a user-defined pattern. Errors: None. See also: SetFillPattern (105) SetGraphBufSize Declaration: Procedure SetGraphBufSize (BufSize : Word); Description: SetGraphBufSize sets the graphical bu er size. The default size is 4Kb Errors: None. See also: SetGraphMode Declaration: Procedure SetGraphMode (Mode : Integer); Description: SetGraphMode sets the graphical mode and clears the screen. Errors: None. See also: InitGraph (100) 105 5.3. FUNCTIONS AND PROCEDURES SetLineStyle Declaration: Procedure SetLineStyle (LineStyle,Pattern,Width : Word); Description: SetLineStyle sets the drawing style for lines. You can specify a LineStyle which is one of the following pre-defined constants: *Solidln=0; draws a solid line. *Dottedln=1; Draws a dotted line. *Centerln=2; draws a non-broken centered line. *Dashedln=3; draws a dashed line. *UserBitln=4; Draws a User-defined bit pattern. If UserBitln is specified then Pattern contains the bit pattern. In all another cases, Pattern is ignored. The parameter Width indicates how thick the line should be. You can specify one of the following pre-defined constants: *NormWidth=1 *ThickWidth=3 Errors: None. See also: GetLineSettings (96) SetPalette Declaration: Procedure SetPalette (ColorNr : Word; NewColor : ShortInt); Description: SetPalette changes the ColorNr-th entry in the palette to NewColor Errors: None. See also: SetAllPallette (104),SetRGBPalette (106) SetRGBPalette Declaration: Procedure SetRGBPalette (ColorNr,Red,Green,Blue : Integer); Description: SetRGBPalette sets the ColorNr-th entry in the palette to the color with RGB- values Red, Green Blue. Errors: None. See also: SetAllPallette (104), SetPalette (106) SetTextJustify Declaration: Procedure SetTextJustify (Horizontal,Vertical : Word); Description: SetTextJustify controls the placement of new text, relative to the (graphical) cursor position. Horizontal controls horizontal placement, and can be one of the following pre-defined constants: *LeftText=0; Text is set left of the pointer. *CenterText=1; Text is set centered horizontally on the pointer. *RightText=2; Text is set to the right of the pointer. 106 5.3. FUNCTIONS AND PROCEDURES Vertical controls the vertical placement of the text, relative to the (graphical) cursor position. Its value can be one of the following pre-defined constants : *BottomText=0; Text is placed under the pointer. *CenterText=1; Text is placed centered vertically on the pointer. *TopText=2;Text is placed above the pointer. Errors: None. See also: OutText (102), OutTextXY (102) SetTextStyle Declaration: Procedure SetTextStyle (Font,Direction,Magnitude : Word); Description: SetTextStyle controls the style of text to be put on the screen. pre-defined constants for Font are: *DefaultFont=0; *TriplexFont=2; *SmallFont=2; *SansSerifFont=3; *GothicFont=4; Pre-defined constants for Direction are : *HorizDir=0; *VertDir=1; Errors: None. See also: GetTextSettings (98) SetUserCharSize Declaration: Procedure SetUserCharSize (Xasp1,Xasp2,Yasp1,Yasp2 : Word); Description: Sets the width and height of vector-fonts. The horizontal size is given by Xasp1/Xasp2, and the vertical size by Yasp1/Yasp2. Errors: None. See also: SetTextStyle (107) SetViewPort Declaration: Procedure SetViewPort (X1,Y1,X2,Y2 : Integer; Clip : Boolean); Description: Sets the current graphical view-port (window) to the rectangle defined by the top- left corner (X1,Y1) and the bottom-right corner (X2,Y2). If Clip is true, anything drawn outside the view-port (window) will be clipped (i.e. not drawn). Coordinates specified after this call are relative to the top-left corner of the view-port. Errors: None. See also: GetViewSettings (98) 107 5.3. FUNCTIONS AND PROCEDURES SetVisualPage Declaration: Procedure SetVisualPage (Page : Word); Description: SetVisualPage sets the video page to page number Page. Errors: None See also: SetActivePage (104) SetWriteMode Declaration: Procedure SetWriteMode (Mode : Integer); Description: SetWriteMode controls the drawing of lines on the screen. It controls the binary operation used when drawing lines on the screen. Mode can be one of the following pre-defined constants: *CopyPut=0; *XORPut=1; Errors: None. See also: TextHeight Declaration: Function TextHeight (S : String) : Word; Description: TextHeight returns the height (in pixels) of the string S in the current font and text-size. Errors: None. See also: TextWidth (108) TextWidth Declaration: Function TextWidth (S : String) : Word; Description: TextHeight returns the width (in pixels) of the string S in the current font and text-size. Errors: None. See also: TextHeight (108) 108 Chapter 6 The HEAPTRC unit. This chapter describes the HEAPTRC unit for Free Pascal. It was written by Pierre Muller. 6.1 Purpose The HEAPTRC unit can be used to debug your memory allocation/deallocation. It keeps track of the calls to getmem/freemem, and, implicitly, of New/Dispose statements. When the program exits, or when you request it explicitly. It displays the total memory used, and then dumps a list of blocks that were allocated but not freed. It also displays where the memory was allocated. If there are any inconsistencies, such as memory blocks being allocated or freed twice, or a memory block that is released but with wrong size, this will be displayed also. The information that is stored/displayed can be customized using some constants. 6.2 Usage All that you need to do is to include heaptrc in the uses clause of your program. Make sure that it is the first unit in the clause, otherwise memory allocated in initialization code of units that precede the heaptrc unit will not be accounted for, causing an incorrect memory usage report. The following example shows how to use the heaptrc unit. Program heapex ; { Program used to demonstrate the usage of heaptrc unit } Uses heaptrc ; Var P1 : Longint ; P2 : Pointer ; I : l o n g i n t ; begin 109 6.2. USAGE New( P1 ) ; // causes p r e v i o u s a l l o c a t i o n not to be de-a l l o c a t e d New( P1 ) ; Dispose ( P1 ) ; For I :=1 to 10 do begin GetMem ( P2 , 1 2 8 ) ; // When I is even , d e a l l o c a t e block . We l o o s e 5 times 128 // bytes t h i s way . I f ( I mod 2 ) = 0 Then FreeMem( P2 , 1 2 8 ) ; end ; GetMem( P2 , 1 2 8 ) ; // This w i l l provoke an e r r o r and a memory dump Freemem ( P2 , 6 4 ) ; end . This is the memory dump shown when running this program: Marked memory at 08052C48 invalid Wrong size : 128 allocated 64 freed 0x0804C29C 0x080509E2 0x080480A4 0x00000000 Heap dump by heaptrc unit 13 memory blocks allocated : 1416/1424 6 memory blocks freed : 708/712 7 unfreed memory blocks : 708 True heap size : 2097152 True free heap : 2096040 Should be : 2096104 Call trace for block 0x08052C48 size 128 0x080509D6 0x080480A4 Call trace for block 0x08052B98 size 128 0x08050992 0x080480A4 Call trace for block 0x08052AE8 size 128 0x08050992 0x080480A4 Call trace for block 0x08052A38 size 128 0x08050992 0x080480A4 Call trace for block 0x08052988 size 128 0x08050992 0x080480A4 Call trace for block 0x080528D8 size 128 0x08050992 0x080480A4 Call trace for block 0x080528A0 size 4 0x08050961 0x080480A4 110 6.3. CONSTANTS, TYPES AND VARIABLES 6.3 Constants, Types and variables The FillExtraInfoType is a procedural type used in the SetExtraInfo (112) call. type FillExtraInfoType = procedure(p : pointer ); The following typed constants allow to fine-tune the standard dump of the memory usage by DumpHeap (111): const t r a c e s i z e = 8; q u i c k t r a c e : boolean = true ; HaltOnError : boolean = true ; k e e p r e l e a s e d : boolean = f a l s e ; Tracesize specifies how many levels of calls are displayed of the call stack during the memory dump. If you specify keepreleased:=True then half the TraceSize is reserved for the GetMem call stack, and the other half is reserved for the FreeMem call stack. For example, the default value of 8 will cause eight levels of call frames to be dumped for the getmem call if keepreleased is False. If KeepReleased is true, then 4 levels of call frames will be dumped for the GetMem call and 4 frames wil be dumped for the FreeMem call. If you want to change this value, you must recode the heaptrc unit. Quicktrace determines whether the memory manager checks whether a block that is about to be released is allocated correctly. This is a rather time consuming search, and slows program execution significantly, so by default it is set to False. If HaltOnError is set to True then an illegal call to FreeMem will cause the memory manager to execute a halt(1) instruction, causing a memory dump. By Default it is set to True. If keepreleased is set to true, then a list of freed memory blocks is kept. This is useful if you suspect that the same memory block is released twice. However, this option is very memory intensive, so use it sparingly, and only when it's really necessary. 6.4 Functions and procedures DumpHeap Declaration: procedure DumpHeap; Description: DumpHeap dumps to standard output a summary of memory usage. It is called automatically by the heaptrc unit when your program exits (by instaling an exit procedure), but it can be called at any time Errors: None. See also: MarkHeap (111) MarkHeap Declaration: procedure MarkHeap; Description: MarkHeap marks all memory blocks with a special signature. You can use this if you think that you corruped the memory. 111 6.4. FUNCTIONS AND PROCEDURES Errors: None. See also: DumpHeap (111) SetExtraInfo Declaration: procedure SetExtraInfo( size : longint;func : FillExtraInfoType); Description: You can use SetExtraInfo to store extra info in the blocks that the heaptrc unit reserves when tracing getmem calls. Size indicates the size (in bytes) that the trace mechanism should reserve for your extra information. For each call to getmem, func will be called, and passed a pointer to the memory reserved. When dumping the memory summary, the extra info is shown as Longint values. Errors: You can only call SetExtraInfo if no memroy has been allocated yet. If memory was already allocated prior to the call to SetExtraInfo, then an error will be displayed on standard error output, and a DumpHeap (111) is executed. See also: DumpHeap (111) Program heapex ; { Program used to demonstrate the usage of heaptrc unit } Uses heaptrc ; Var P1 : Longint ; P2 : Pointer ; I : l o n g i n t ; Marker : Longint ; Procedure SetMarker ( P : p o i n t e r ) ; Type PLongint = Longint ; begin PLongint (P) := Marker ; end ; Procedure Part1 ; begin // Blocks a l l o c a t e d here are marked with $FFAAFFAA = -5570646 Marker := $FFAAFFAA; New( P1 ) ; New( P1 ) ; Dispose ( P1 ) ; For I :=1 to 10 do begin GetMem ( P2 , 1 2 8 ) ; I f ( I mod 2) = 0 Then FreeMem( P2 , 1 2 8 ) ; end ; GetMem( P2 , 1 2 8 ) ; end ; 112 6.4. FUNCTIONS AND PROCEDURES Procedure Part2 ; begin // Blocks a l l o c a t e d here are marked with $FAFAFAFA = -84215046 Marker := $FAFAFAFA; New( P1 ) ; New( P1 ) ; Dispose ( P1 ) ; For I :=1 to 10 do begin GetMem ( P2 , 1 2 8 ) ; I f ( I mod 2 ) = 0 Then FreeMem( P2 , 1 2 8 ) ; end ; GetMem( P2 , 1 2 8 ) ; end ; begin S e t E x t r a I n f o ( SizeOf ( Marker ) , @SetMarker ) ; Writeln ( ' Part 1' ) ; part1 ; Writeln ( ' Part 2' ) ; part2 ; end . 113 Chapter 7 The IPC unit. This chapter describes the IPC unit for Free Pascal. It was written for linux by Micha¨el Van Canneyt. It gives all the functionality of system V Inter-Process Communication: shared memory, semaphores and messages. The chapter is divided in 2 sections: * The first section lists types, constants and variables from the interface part of the unit. * The second section describes the functions defined in the unit. 7.1 Types, Constants and variables : Variables VarIPCerror : longint; The IPCerror variable is used to report errors, by all calls. Constants Const IPC_CREAT = 1 shl 9; { create if key is nonexistent } IPC_EXCL = 2 shl 9; { fail if key exists } IPC_NOWAIT = 4 shl 9; { return error on wait } These constants are used in the various xxxget calls. IPC_RMID = 0; { remove resource } IPC_SET = 1; { set ipc_perm options } IPC_STAT = 2; { get ipc_perm options } IPC_INFO = 3; { see ipcs } These constants can be passed to the various xxxctl calls. const MSG_NOERROR = 1 shl 12; 114 7.1. TYPES, CONSTANTS AND VARIABLES : MSG_EXCEPT = 2 shl 12; MSGMNI = 128; MSGMAX = 4056; MSGMNB = 16384; These constants are used in the messaging system, they are not for use by the programmer. const SEM_UNDO = $1000; GETPID = 11; GETVAL = 12; GETALL = 13; GETNCNT = 14; GETZCNT = 15; SETVAL = 16; SETALL = 17; These constants call be specified in the semop (123) call. SEMMNI = 128; SEMMSL = 32; SEMMNS = (SEMMNI * SEMMSL); SEMOPM = 32; SEMVMX = 32767; These constanst are used internally by the semaphore system, they should not be used by the programmer. const SHM_R = 4 shl 6; SHM_W = 2 shl 6; SHM_RDONLY = 1 shl 12; SHM_RND = 2 shl 12; SHM_REMAP = 4 shl 12; SHM_LOCK = 11; SHM_UNLOCK = 12; These constants are used in the shmctl (130) call. Types TypeTKey = Longint; TKey is the type returned by the ftok (119) key generating function. type PIPC_Perm = ^TIPC_Perm; TIPC_Perm = record key : TKey; uid, gid, 115 7.1. TYPES, CONSTANTS AND VARIABLES : cuid, cgid, mode, seq : Word; end; The TIPC Perm structure is used in all IPC systems to specify the permissions. Type PSHMid_DS = ^TSHMid_ds; TSHMid_ds = record shm_perm : TIPC_Perm; shm_segsz : longint; shm_atime : longint; shm_dtime : longint; shm_ctime : longint; shm_cpid : word; shm_lpid : word; shm_nattch : integer; shm_npages : word; shm_pages : Pointer; attaches : pointer; end; The TSHMid ds strucure is used in the shmctl (130) call to set or retrieve settings concerning shared memory. type PSHMinfo = ^TSHMinfo; TSHMinfo = record shmmax : longint; shmmin : longint; shmmni : longint; shmseg : longint; shmall : longint; end; The TSHMinfo record is used by the shared memory system, and should not be accessed by the programer directly. type PMSG = ^TMSG; TMSG = record msg_next : PMSG; msg_type : Longint; msg_spot : PChar; msg_stime : Longint; msg_ts : Integer; end; The TMSG record is used in the handling of message queues. There should be few cases where the programmer needs to access this data. type 116 7.1. TYPES, CONSTANTS AND VARIABLES : PMSQid_ds = ^TMSQid_ds; TMSQid_ds = record msg_perm : TIPC_perm; msg_first : PMsg; msg_last : PMsg; msg_stime : Longint; msg_rtime : Longint; msg_ctime : Longint; wwait : Pointer; rwait : pointer; msg_cbytes : word; msg_qnum : word; msg_qbytes : word; msg_lspid : word; msg_lrpid : word; end; The TMSQid ds record is returned by the msgctl (120) call, and contains all data about a message queue. PMSGbuf = ^TMSGbuf; TMSGbuf = record mtype : longint; mtext : array[0..0] of char; end; The TMSGbuf record is a record containing the data of a record. you should never use this record directly, instead you should make your own record that follows the structure of the TMSGbuf record, but that has a size that is big enough to accomodate your messages. The mtype field should always be present, and should always be filled. Type PMSGinfo = ^TMSGinfo; TMSGinfo = record msgpool : Longint; msgmap : Longint; msgmax : Longint; msgmnb : Longint; msgmni : Longint; msgssz : Longint; msgtql : Longint; msgseg : Word; end; The TMSGinfo record is used internally by the message queue system, and should not be used by the programmer directly. Type PSEMid_ds = ^PSEMid_ds; TSEMid_ds = record sem_perm : tipc_perm; sem_otime : longint; sem_ctime : longint; 117 7.1. TYPES, CONSTANTS AND VARIABLES : sem_base : pointer; sem_pending : pointer; sem_pending_last : pointer; undo : pointer; sem_nsems : word; end; The TSEMid ds structure is returned by the semctl (124) call, and contains all data concerning a semahore. Type PSEMbuf = ^TSEMbuf; TSEMbuf = record sem_num : word; sem_op : integer; sem_flg : integer; end; The TSEMbuf record us use in the semop (123) call, and is used to specify which operations you want to do. Type PSEMinfo = ^TSEMinfo; TSEMinfo = record semmap : longint; semmni : longint; semmns : longint; semmnu : longint; semmsl : longint; semopm : longint; semume : longint; semusz : longint; semvmx : longint; semaem : longint; end; The TSEMinfo record is used internally by the semaphore system, and should not be used diirectly. Type PSEMun = ^TSEMun; TSEMun = record case longint of 0 : ( val : longint ); 1 : ( buf : PSEMid_ds ); 2 : ( arr : PWord ); 3 : ( padbuf : PSeminfo ); 4 : ( padpad : pointer ); end; The TSEMun variant record (actually a C union) is used in the semctl (124) call. 118 7.2. FUNCTIONS AND PROCEDURES 7.2 Functions and procedures ftok Declaration: Function ftok (Path : String; ID : char) : TKey; Description: ftok returns a key that can be used in a semget (123),shmget (129) or msgget (119) call to access a new or existing IPC resource. Path is the name of a file in the file system, ID is a character of your choice. The ftok call does the same as it's C couterpart, so a pascal program and a C program will access the same resource if they use the same Path and ID Errors: ftok returns -1 if the file in Path doesn't exist. See also: semget (123),shmget (129),msgget (119) For an example, see msgctl (120), semctl (124), shmctl (130). msgget Declaration: Function msgget(key: TKey; msgflg:longint):longint; Description: msgget returns the ID of the message queue described by key. Depending on the flags in msgflg, a new queue is created. msgflg can have one or more of the following values (combined by ORs): IPC CREATThe queue is created if it doesn't already exist. IPC EXCLIf used in combination with IPC CREAT, causes the call to fail if the queue already exists. It cannot be used by itself. Optionally, the flags can be ORed with a permission mode, which is the same mode that can be used in the file system. Errors: On error, -1 is returned, and IPCError is set. See also: ftok (119),msgsnd (119), msgrcv (120), msgctl (120), semget (2) For an example, see msgctl (120). msgsnd Declaration: Function msgsnd(msqid:longint; msgp: PMSGBuf; msgsz: longint; msgflg:longint): Boolean; Description: msgsend sends a message to a message queue with ID msqid. msgp is a pointer to a message bu er, that should be based on the TMsgBuf type. msgsiz is the size of the message (NOT of the message bu er record !) The msgflg can have a combination of the following values (ORed together): 0No special meaning. The message will be written to the queue. If the queue is full, then the process is blocked. IPC NOWAITIf the queue is full, then no message is written, and the call returns immediatly. The function returns True if the message was sent successfully, False otherwise. 119 7.2. FUNCTIONS AND PROCEDURES Errors: In case of error, the call returns False, and IPCerror is set. See also: msgget (119), msgrcv (120), seefmsgctl For an example, see msgctl (120). msgrcv Declaration: Function msgrcv(msqid:longint; msgp: PMSGBuf; msgsz: longint; msgtyp:longint; msgflg:longint): Boolean; Description: msgrcv retrieves a message of type msgtyp from the message queue with ID msqid. msgtyp corresponds to the mtype field of the TMSGbuf record. The message is stored in the MSGbuf structure pointed to by msgp. The msgflg parameter can be used to control the behaviour of the msgrcv call. It consists of an ORed combination of the following flags: 0No special meaning. IPC NOWAITif no messages are available, then the call returns immediatly, with the ENOMSG error. MSG NOERRORIf the message size is wrong (too large), no error is generated, instead the message is truncated. Normally, in such cases, the call returns an error (E2BIG) The function returns True if the message was received correctly, False otherwise. Errors: In case of error, False is returned, and IPCerror is set. See also: msgget (119), msgsnd (119), msgctl (120) For an example, see msgctl (120). msgctl Declaration: Function msgctl(msqid:longint; cmd: longint; buf: PMSQid ds): Boolean; Description: msgctl performs various operations on the message queue with id ID. Which op- eration is performed, depends on the cmd parameter, which can have one of the following values: IPC STATIn this case, the msgctl call fills the TMSQid ds structure with infor- mation about the message queue. IPC SETin this case, the msgctl call sets the permissions of the queue as specified in the ipc perm record inside buf. IPC RMIDIf this is specified, the message queue will be removed from the system. buf contains the data that are needed by the call. It can be Nil in case the message queue should be removed. The function returns True if successfull, False otherwise. Errors: On error, False is returned, and IPCerror is set accordingly. See also: msgget (119), msgsnd (119), msgrcv (120) 120 7.2. FUNCTIONS AND PROCEDURES program msgtool ; Uses ipc ; Type PMyMsgBuf = TMyMsgBuf ; TMyMsgBuf = record mtype : Longint ; mtext : str ing [ 2 5 5 ] ; end ; Procedure DoError ( Const Msg : string ) ; begin Writeln ( msg , ' r e t u r n e d an e r r o r : ' , i p c e r r o r ) ; halt ( 1 ) ; end ; Procedure SendMessage ( Id : Longint ; Var Buf : TMyMsgBuf ; MType : Longint ; Const MText : String ) ; begin Writeln ( ' Sending message . ' ) ; Buf . mtype := mtype ; Buf . Mtext := mtext ; I f not msgsnd ( Id , PMsgBuf ( @Buf ) , 2 5 6 , 0 ) then DoError ( ' msgsnd ' ) ; end ; Procedure ReadMessage ( ID : Longint ; Var Buf : TMyMsgBuf ; MType : l o n g i n t ) ; begin Writeln ( ' Reading message . ' ) ; Buf . MType:=MType; I f msgrcv ( ID , PMSGBuf( @Buf ) , 2 5 6 , mtype , 0 ) then Writeln ( ' Type : ' , buf . mtype , ' Text : ' , buf . mtext ) else DoError ( ' msgrcv ' ) ; end ; Procedure RemoveQueue ( ID : Longint ) ; begin I f msgctl ( id , IPC RMID, Nil ) then Writeln ( ' Removed Queue with id ' , Id ) ; end ; Procedure ChangeQueueMode ( ID , mode : l o n g i n t ) ; Var QueueDS : TMSQid ds ; 121 7.2. FUNCTIONS AND PROCEDURES begin I f Not msgctl ( Id , IPC STAT, @QueueDS ) then DoError ( ' msgctl : s t a t ' ) ; Writeln ( ' Old p e r m i s s i o n s : ' , QueueDS . msg perm . mode ) ; QueueDS . msg perm . mode:=Mode; i f msgctl ( ID , IPC SET, @QueueDS ) then Writeln ( ' New p e r m i s s i o n s : ' , QueueDS . msg perm . mode) else DoError ( ' msgctl : IPC SET' ) ; end ; procedure usage ; begin Writeln ( ' Usage : msgtool s ( end ) < type > (max 255 c h a r a c t e r s ) ' ) ; Writeln ( ' r ( e c e i v e ) < type >' ) ; Writeln ( ' d( e l e t e ) ' ) ; Writeln ( ' m( ode ) < decimal mode>' ) ; halt ( 1 ) ; end ; Function StrToInt ( S : String ) : l o n g i n t ; Var M : l o n g i n t ; C : I n t e g e r ; begin val ( S ,M, C) ; I f C<>0 Then DoError ( ' StrToInt : ' +S ) ; StrToInt :=M; end ; VarKey : TKey; ID : l o n g i n t ; Buf : TMyMsgBuf ; begin I f Paramcount<1 then Usage ; key := Ftok ( ' . ' , 'M' ) ; ID := msgget ( key , IPC CREAT or 4 3 8 ) ; I f ID <0 then DoError ( ' MsgGet ' ) ; Case upCase ( Paramstr ( 1 ) [ 1 ] ) of ' S ' : I f ParamCount<>3 then Usage else SendMessage ( id , Buf , StrToInt ( Paramstr ( 2 ) ) , paramstr ( 3 ) ) ; ' R' : I f ParamCount<>2 then Usage else ReadMessage ( id , buf , s t r t o i n t ( Paramstr ( 2 ) ) ) ; ' D' : I f ParamCount<>1 then Usage 122 7.2. FUNCTIONS AND PROCEDURES else RemoveQueue ( ID ) ; 'M' : I f ParamCount<>2 then Usage else ChangeQueueMode ( id , s t r t o i n t ( paramstr ( 2 ) ) ) ; else Usage end ; end . semget Declaration: Function semget(key:Tkey; nsems:longint; semflg:longint): longint; Description: msgget returns the ID of the semaphore set described by key. Depending on the flags in semflg, a new queue is created. semflg can have one or more of the following values (combined by ORs): IPC CREATThe queue is created if it doesn't already exist. IPC EXCLIf used in combination with IPC CREAT, causes the call to fail if the set already exists. It cannot be used by itself. Optionally, the flags can be ORed with a permission mode, which is the same mode that can be used in the file system. if a new set of semaphores is created, then there will be nsems semaphores in it. Errors: On error, -1 is returned, and IPCError is set. See also: ftok (119), semop (123), semctl (124) semop Declaration: Function semop(semid:longint; sops: pointer; nsops: cardinal): Boolean; Description: semop performs a set of operations on a message queue. sops points to an array of type TSEMbuf. The array should contain nsops elements. The fields of the TSEMbuf structure TSEMbuf = record sem_num : word; sem_op : integer; sem_flg : integer; should be filled as follows: sem numThe number of the semaphore in the set on which the operation must be performed. sem opThe operation to be performed. The operation depends on the sign of sem op 1.A positive number is simply added to the current value of the semaphore. 2.If 0 (zero) is specified, then the process is suspended until the specified semaphore reaches zero. 123 7.2. FUNCTIONS AND PROCEDURES 3.If a negative number is specified, it is substracted from the current value of the semaphore. If the value would become negative then the process is suspended until the value becomes big enough, unless IPC NOWAIT is specified in the sem flg. sem flgOptional flags: if IPC NOWAIT is specified, then the calling process will never be suspended. The function returns True if the operations were successful, False otherwise. Errors: In case of error, False is returned, and IPCerror is set. See also: semget (123), semctl (124) semctl Declaration: Function semctl(semid:longint; semnum:longint; cmd:longint; var arg: tsemun): longint; Description: semctl performs various operations on the semaphore semnum w ith semaphore set id ID. The arg parameter supplies the data needed for each call. This is a variant record that should be filled di erently, according to the command: Type TSEMun = record case longint of 0 : ( val : longint ); 1 : ( buf : PSEMid_ds ); 2 : ( arr : PWord ); 3 : ( padbuf : PSeminfo ); 4 : ( padpad : pointer ); end; Which operation is performed, depends on the cmd parameter, which can have one of the following values: IPC STATIn this case, the arg record should have it's buf field set to the address of a TSEMid ds record. The semctl call fills this TSEMid ds structure with information about the semaphore set. IPC SETIn this case, the arg record should have it's buf field set to the address of a TSEMid ds record. The semctl call sets the permissions of the queue as specified in the ipc perm record. IPC RMIDIf this is specified, the semaphore set is removed from from the system. GETALLIn this case, the arr field of arg should point to a memory area where the values of the semaphores will be stored. The size of this memory area is SizeOf(Word)* Number of semaphores in the set. This call will then fill the memory array with all the values of the semaphores. GETNCNTThis will fill the val field of the arg union with the bumber of processes waiting for resources. GETPIDsemctl returns the process ID of the process that performed the last semop (123) call. GETVALsemctl returns the value of the semaphore with number semnum. 124 7.2. FUNCTIONS AND PROCEDURES GETZCNTsemctl returns the number of processes waiting for semaphores that reach value zero. SETALLIn this case, the arr field of arg should point to a memory area where the values of the semaphores will be retrieved from. The size of this memory area is SizeOf(Word)* Number of semaphores in the set. This call will then set the values of the semaphores from the memory array. SETVALThis will set the value of semaphore semnum to the value in the val field of the arg parameter. The function returns -1 on error. Errors: The function returns -1 on error, and IPCerror is set accordingly. See also: semget (123), semop (123) Program semtool ; { Program to demonstrat the use of semaphores } Uses ipc ; Const MaxSemValue = 5; Procedure DoError ( Const Msg : String ) ; begin Writeln ( ' Error : ' , msg , ' Code : ' , IPCerror ) ; Halt ( 1 ) ; end ; Function getsemval ( ID , Member : l o n g i n t ) : l o n g i n t ; Var S : TSEMun; begin GetSemVal := SemCtl ( id , member , GETVAL, S ) ; end ; Procedure DispVal ( ID , member : l o n g i n t ) ; begin writeln ( ' Value fo r member ' , member , ' i s ' , GetSemVal ( ID , Member ) ) ; end ; Function GetMemberCount ( ID : Longint ) : l o n g i n t ; Var opts : TSEMun; semds : TSEMid ds ; begin opts . buf :=@semds ; I f semctl ( Id , 0 , IPC STAT, opts )<>-1 then GetMemberCount := semds . sem nsems else 125 7.2. FUNCTIONS AND PROCEDURES GetMemberCount :=-1; end ; Function OpenSem ( Key : TKey ) : Longint ; begin OpenSem:= semget ( Key , 0 , 4 3 8 ) ; I f OpenSem=-1 then DoError ( ' OpenSem ' ) ; end ; Function CreateSem ( Key : TKey ; Members : Longint ) : Longint ; Var Count : Longint ; Semopts : TSemun ; begin I f members>semmsl then DoError ( ' Sorry , maximum number of semaphores in set exceeded ' ) ; Writeln ( ' Trying to c r e a t e a new semaphore set with ' , members , ' members . ' ) ; CreateSem := semget ( key , members , IPC CREAT or IPC Excl or 4 3 8 ) ; I f CreateSem =-1 then DoError ( ' Semaphore set a l r e a d y e x i s t s . ' ) ; Semopts . val :=MaxSemValue ; { I n i t i a l value of semaphores } For Count :=0 to Members-1 do semctl ( CreateSem , count , s e t v a l , semopts ) ; end ; Procedure lockSem ( ID , Member : Longint ) ; Var lock : TSEMbuf ; begin With lock do begin sem num:=0; sem op:=-1; sem flg :=IPC NOWAIT; end ; i f ( member <0) or ( member>GetMemberCount ( ID )-1) then DoError ( ' semaphore member out of range ' ) ; i f getsemval ( ID , member )=0 then DoError ( ' Semaphore r e s o u r c e s exhausted ( no lock ) ' ) ; lock . sem num:=member ; Writeln ( ' Attempting to lock member ' , member , ' of semaphore ' , ID ) ; i f not semop ( Id , @lock , 1 ) then DoError ( ' Lock f a i l e d ' ) else Writeln ( ' Semaphore r e s o u r c e s decremented by one ' ) ; d i s p v a l ( ID , Member ) ; end ; Procedure UnlockSem ( ID , Member : Longint ) ; 126 7.2. FUNCTIONS AND PROCEDURES Var Unlock : TSEMbuf ; begin With Unlock do begin sem num:=0; sem op :=1; sem flg :=IPC NOWAIT; end ; i f ( member <0) or ( member>GetMemberCount ( ID )-1) then DoError ( ' semaphore member out of range ' ) ; i f getsemval ( ID , member)=MaxSemValue then DoError ( ' Semaphore not locked ' ) ; Unlock . sem num:=member ; Writeln ( ' Attempting to unlock member ' , member , ' of semaphore ' , ID ) ; i f not semop ( Id , @unlock , 1 ) then DoError ( ' Unlock f a i l e d ' ) else Writeln ( ' Semaphore r e s o u r c e s incremented by one ' ) ; d i s p v a l ( ID , Member ) ; end ; Procedure RemoveSem ( ID : l o n g i n t ) ; var S : TSemun ; begin I f semctl ( Id , 0 , IPC RMID, s )<>-1 then Writeln ( ' Semaphore removed ' ) else DoError ( ' Couldn ' ' t remove semaphore ' ) ; end ; Procedure ChangeMode ( ID , Mode : l o n g i n t ) ; Var rc : l o n g i n t ; opts : TSEMun; semds : TSEMid ds ; begin opts . buf :=@semds ; I f not semctl ( Id , 0 , IPC STAT, opts )<>-1 then DoError ( ' Couldn ' ' t s t a t semaphore ' ) ; Writeln ( ' Old p e r m i s s i o n s were : ' , semds . sem perm . mode ) ; semds . sem perm . mode:=mode ; I f semctl ( id , 0 , IPC SET, opts )<>-1 then Writeln ( ' Set p e r m i s s i o n s to ' , mode) else DoError ( ' Couldn ' ' t set p e r m i s s i o n s ' ) ; end ; Procedure PrintSem ( ID : l o n g i n t ) ; 127 7.2. FUNCTIONS AND PROCEDURES Var I , cnt : l o n g i n t ; begin cnt := getmembercount ( ID ) ; Writeln ( ' Semaphore ' , ID , ' has ' , cnt , ' Members ' ) ; For I :=0 to cnt -1 Do DispVal ( id , i ) ; end ; Procedure USage ; begin Writeln ( ' Usage : semtool c ( r e a t e ) < count >' ) ; Writeln ( ' l ( ock ) ' ) ; Writeln ( ' u( nlock ) ' ) ; Writeln ( ' d( e l e t e ) ' ) ; Writeln ( ' m( ode ) ' ) ; halt ( 1 ) ; end ; Function StrToInt ( S : String ) : l o n g i n t ; Var M : l o n g i n t ; C : I n t e g e r ; begin val ( S ,M, C) ; I f C<>0 Then DoError ( ' StrToInt : ' +S ) ; StrToInt :=M; end ; Var Key : TKey ; ID : Longint ; begin I f ParamCount<1 then USage ; key := ftok ( ' . ' , ' s ' ) ; Case UpCase( Paramstr ( 1 ) [ 1 ] ) of ' C' : begin i f paramcount<>2 then usage ; CreateSem ( key , s t r t o i n t ( paramstr ( 2 ) ) ) ; end ; ' L ' : begin i f paramcount<>2 then usage ; ID :=OpenSem ( key ) ; LockSem ( ID , s t r t o i n t ( paramstr ( 2 ) ) ) ; end ; ' U' : begin i f paramcount<>2 then usage ; ID :=OpenSem ( key ) ; UnLockSem ( ID , s t r t o i n t ( paramstr ( 2 ) ) ) ; end ; 'M' : begin i f paramcount<>2 then usage ; 128 7.2. FUNCTIONS AND PROCEDURES ID :=OpenSem ( key ) ; ChangeMode ( ID , s t r t o i n t ( paramstr ( 2 ) ) ) ; end ; ' D' : Begin ID :=OpenSem( Key ) ; RemoveSem( Id ) ; end ; ' P' : begin ID :=OpenSem( Key ) ; PrintSem ( Id ) ; end ; else Usage end ; end . shmget Declaration: Function shmget(key: Tkey; Size:longint; flag:longint):longint; Description: shmget returns the ID of a shared memory block, described by key. Depending on the flags in flag, a new memory block is created. flag can have one or more of the following values (combined by ORs): IPC CREATThe queue is created if it doesn't already exist. IPC EXCLIf used in combination with IPC CREAT, causes the call to fail if the queue already exists. It cannot be used by itself. Optionally, the flags can be ORed with a permission mode, which is the same mode that can be used in the file system. if a new memory block is created, then it will have size Size semaphores in it. Errors: On error, -1 is returned, and IPCError is set. See also: shmat Declaration: Function shmat (shmid:longint; shmaddr:pchar; shmflg:longint):pchar; Description: shmat attaches a shared memory block with identified shmid to the current process. The function returns a pointer to the shared memory block. If shmaddr is Nil, then the system chooses a free unmapped memory region, as high up in memory space as possible. If shmaddr is non-nil, and SHM RND is in shmflg, then the returned address is shmaddr, rounded down to SHMLBA. If SHM RND is not specified, then shmaddr must be a page-aligned address. The parameter shmflg can be used to control the behaviour of the shmat call. It consists of a ORed combination of the following costants: SHM RNDThe suggested address in shmaddr is rounded down to SHMLBA. 129 7.2. FUNCTIONS AND PROCEDURES SHM RDONLYthe shared memory is attached for read access only. Otherwise the memory is attached for read-write. The process then needs read-write permissions to access the shared memory. Errors: If an error occurs, -1 is returned, and IPCerror is set. See also: shmget (129), shmdt (130), shmctl (130) For an example, see shmctl (130). shmdt Declaration: Function shmdt (shmaddr:pchar):boolean; Description: shmdt detaches the shared memory at address shmaddr. This shared memory block is unavailable to the current process, until it is attached again by a call to shmat (129). The function returns True if the memory block was detached successfully, False otherwise. Errors: On error, False is returned, and IPCerror is set. See also: shmget (129), shmat (129), shmctl (130) shmctl Declaration: Function shmctl(shmid:longint; cmd:longint; buf: pshmid ds): Boolean; Description: shmctl performs various operations on the shared memory block identified by identifier shmid. The buf parameter points to a TSHMid ds record. The cmd parameter is used to pass which operation is to be performed. It can have one of the following values : IPC STATshmctl fills the TSHMid ds record that buf points to with the available information about the shared memory block. IPC SETapplies the values in the ipc perm record that buf points to, to the shared memory block. IPC RMIDthe shared memory block is destroyed (after all processes to which the block is attached, have detached from it). If successful, the function returns True, False otherwise. Errors: If an error occurs, the function returns False, and IPCerror is set. See also: shmget (129), shmat (129), shmdt (130) Program shmtool ; uses ipc , s t r i n g s ; Const SegSize = 100; var key : Tkey ; shmid , cntr : l o n g i n t ; s e g p t r : pchar ; 130 7.2. FUNCTIONS AND PROCEDURES Procedure USage ; begin Writeln ( ' Usage : shmtool w( r i t e ) text ' ) ; writeln ( ' r ( ead ) ' ) ; writeln ( ' d( e l e t e ) ' ) ; writeln ( ' m( ode change ) mode ' ) ; halt ( 1 ) ; end ; Procedure Writeshm ( ID : Longint ; ptr : pchar ; S : st ring ) ; begin strpcopy ( ptr , s ) ; end ; Procedure Readshm ( ID : l o n g i n t ; ptr : pchar ) ; begin Writeln ( ' Read : ' , ptr ) ; end ; Procedure removeshm ( ID : Longint ) ; begin shmctl ( ID , IPC RMID, Nil ) ; writeln ( ' Shared memory marked f o r d e l e t i o n ' ) ; end ; Procedure CHangeMode ( ID : l o n g i n t ; mode : String ) ; Var m : word ; code : i n t e g e r ; data : TSHMid ds ; begin val ( mode , m, code ) ; i f code <>0 then usage ; I f Not shmctl ( shmid , IPC STAT, @data ) then begin writeln ( ' Error : shmctl : ' , i p c e r r o r ) ; halt ( 1 ) ; end ; writeln ( ' Old p e r m i s s i o n s : ' , data . shm perm . mode ) ; data . shm perm . mode:=m; I f Not shmctl ( shmid , IPC SET, @data ) then begin writeln ( ' Error : shmctl : ' , i p c e r r o r ) ; halt ( 1 ) ; end ; writeln ( ' New p e r m i s s i o n s : ' , data . shm perm . mode ) ; end ; 131 7.2. FUNCTIONS AND PROCEDURES begin i f paramcount <1 then usage ; key := ftok ( ' . ' , ' S ' ) ; shmid := shmget ( key , s e g s i z e , IPC CREAT or IPC EXCL or 4 3 8 ) ; I f shmid =-1 then begin Writeln ( ' Shared memory e x i s t s . Opening as c l i e n t ' ) ; shmid := shmget ( key , s e g s i z e , 0 ) ; I f shmid = -1 then begin Writeln ( ' shmget : Error ! ' , i p c e r r o r ) ; halt ( 1 ) ; end end else Writeln ( ' Creating new shared memory segment . ' ) ; s e g p t r := shmat ( shmid , n i l , 0 ) ; i f l o n g i n t ( s e g p t r )=-1 then begin Writeln ( ' Shmat : e r r o r ! ' , i p c e r r o r ) ; halt ( 1 ) ; end ; case upcase ( paramstr ( 1 ) [ 1 ] ) of 'W' : writeshm ( shmid , s e g p t r , paramstr ( 2 ) ) ; ' R' : readshm ( shmid , s e g p t r ) ; ' D' : removeshm ( shmid ) ; 'M' : changemode ( shmid , paramstr ( 2 ) ) ; else begin writeln ( paramstr ( 1 ) ) ; usage ; end ; end ; end . 132 Chapter 8 The LINUX unit. This chapter describes the LINUX unit for Free Pascal. The unit was written by Micha¨el van Canneyt. It works only on the Linux operating system. This chapter is divided in 2 sections: * The first section lists all constants, types and variables, as listed in the inter- face section of the LINUX unit. * The second section describes all procedures and functions in the LINUX unit. 8.1 Type, Variable and Constant declarations Types PGlob and TGlob are 2 types used in the Glob (167) function: PGlob = ^TGlob; TGlob = record Name : PChar; Next : PGlob; end; The following types are used in the signal-processing procedures. {$Packrecords 1} SignalHandler = Procedure ( Sig : Integer);cdecl; PSignalHandler = SignalHandler; SignalRestorer = Procedure;cdecl; PSignalrestorer = SignalRestorer; SigActionRec = Record Sa_Handler : Signalhandler; Sa_Mask : Longint; Sa_flags : Integer; Sa_Restorer : SignalRestorer; end; PSigActionRec = ^SigActionRec; Stat is used to store information about a file. It is defined in the syscalls unit. 133 8.1. TYPE, VARIABLE AND CONSTANT DECLARATIONS stat = record dev : word; pad1 : word; ino : longint; mode : word; nlink : word; uid : word; gid : word; rdev : word; pad2 : word; size : longint; blksze : Longint; blocks : Longint; atime : Longint; unused1 : longint; mtime : Longint; unused2 : longint; ctime : Longint; unused3 : longint; unused4 : longint; unused5 : longint; end; Statfs is used to store information about a filesystem. It is defined in the syscalls unit. statfs = record fstype : longint; bsize : longint; blocks : longint; bfree : longint; bavail : longint; files : longint; ffree : longint; fsid : longint; namelen : longint; spare : array [0..6] of longint; end Dir and PDir are used in the OpenDir (176) and ReadDir (178) functions. TDir =record fd : integer; loc : longint; size : integer; buf : pdirent; nextoff: longint; dd_max : integer; lock : pointer; end; PDir =^TDir; Dirent, PDirent are used in the ReadDir (178) function to return files in a direc- tory. 134 8.1. TYPE, VARIABLE AND CONSTANT DECLARATIONS PDirent = ^Dirent; Dirent = Record ino, off : longint; reclen : word; name : string[255] end; Termio and Termios are used with iotcl() calls for terminal handling. Const NCCS = 19; NCC = 8; Type termio = record c_iflag,{ input mode flags } c_oflag,{ output mode flags } c_cflag,{ control mode flags } c_lflag : Word; { local mode flags } c_line : Word; { line discipline - careful, only High byte in use} c_cc : array [0..NCC-1] of char; { control characters } end; termios = record c_iflag, { input mode flags } c_oflag, { output mode flags } c_cflag, { control mode flags } c_lflag : Cardinal; { local mode flags } c_line : char; { line discipline } c_cc : array [0..NCCS-1] of char; { control characters } end; Utimbuf is used in the Utime (189) call to set access and modificaton time of a file. utimbuf = record actime,modtime : Longint; end; For the Select (178) call, the following 4 types are needed: FDSet = Array [0..31] of longint; PFDSet = ^FDSet; TimeVal = Record sec,usec : Longint; end; PTimeVal = ^TimeVal; The Uname (188) function uses the utsname to return information about the current kernel : utsname =record sysname,nodename,release, version,machine,domainname : Array[0..64] of char; end; Its elements are null-terminated C style strings, you cannot access them directly ! 135 8.1. TYPE, VARIABLE AND CONSTANT DECLARATIONS Variables Linuxerror is the variable in which the procedures in the linux unit report errors. LinuxError : Longint; StdErr Is a Text variable, corresponding to Standard Error or diagnostic output. It is connected to file descriptor 2. It can be freely used, and will be closed on exit. StdErr : Text; Constants Constants for setting/getting process priorities : Prio_Process = 0; Prio_PGrp = 1; Prio_User = 2; For testing access rights: R_OK = 4; W_OK = 2; X_OK = 1; F_OK = 0; For signal handling functions : SA_NOCLDSTOP = 1; SA_SHIRQ = $04000000; SA_STACK = $08000000; SA_RESTART = $10000000; SA_INTERRUPT = $20000000; SA_NOMASK = $40000000; SA_ONESHOT = $80000000; SIG_BLOCK = 0; SIG_UNBLOCK = 1; SIG_SETMASK = 2; SIG_DFL = 0 ; SIG_IGN = 1 ; SIG_ERR = -1; SIGHUP = 1; SIGINT = 2; SIGQUIT = 3; SIGILL = 4; SIGTRAP = 5; SIGABRT = 6; SIGIOT = 6; SIGBUS = 7; SIGFPE = 8; SIGKILL = 9; SIGUSR1 = 10; 136 8.1. TYPE, VARIABLE AND CONSTANT DECLARATIONS SIGSEGV = 11; SIGUSR2 = 12; SIGPIPE = 13; SIGALRM = 14; SIGTERM = 15; SIGSTKFLT = 16; SIGCHLD = 17; SIGCONT = 18; SIGSTOP = 19; SIGTSTP = 20; SIGTTIN = 21; SIGTTOU = 22; SIGURG = 23; SIGXCPU = 24; SIGXFSZ = 25; SIGVTALRM = 26; SIGPROF = 27; SIGWINCH = 28; SIGIO = 29; SIGPOLL = SIGIO; SIGPWR = 30; SIGUNUSED = 31; For file control mechanism : F_GetFd = 1; F_SetFd = 2; F_GetFl = 3; F_SetFl = 4; F_GetLk = 5; F_SetLk = 6; F_SetLkW = 7; F_GetOwn = 8; F_SetOwn = 9; For Terminal handling : TCGETS = $5401 ; TCSETS = $5402 ; TCSETSW = $5403 ; TCSETSF = $5404 ; TCGETA = $5405 ; TCSETA = $5406 ; TCSETAW = $5407 ; TCSETAF = $5408 ; TCSBRK = $5409 ; TCXONC = $540A ; TCFLSH = $540B ; TIOCEXCL = $540C ; TIOCNXCL = $540D ; TIOCSCTTY = $540E ; TIOCGPGRP = $540F ; TIOCSPGRP = $5410 ; TIOCOUTQ = $5411 ; 137 8.1. TYPE, VARIABLE AND CONSTANT DECLARATIONS TIOCSTI = $5412 ; TIOCGWINSZ = $5413 ; TIOCSWINSZ = $5414 ; TIOCMGET = $5415 ; TIOCMBIS = $5416 ; TIOCMBIC = $5417 ; TIOCMSET = $5418 ; TIOCGSOFTCAR = $5419 ; TIOCSSOFTCAR = $541A ; FIONREAD = $541B ; TIOCINQ = FIONREAD; TIOCLINUX = $541C ; TIOCCONS = $541D ; TIOCGSERIAL = $541E ; TIOCSSERIAL = $541F ; TIOCPKT = $5420 ; FIONBIO = $5421 ; TIOCNOTTY = $5422 ; TIOCSETD = $5423 ; TIOCGETD = $5424 ; TCSBRKP = $5425 ; TIOCTTYGSTRUCT = $5426 ; FIONCLEX = $5450 ; FIOCLEX = $5451 ; FIOASYNC = $5452 ; TIOCSERCONFIG = $5453 ; TIOCSERGWILD = $5454 ; TIOCSERSWILD = $5455 ; TIOCGLCKTRMIOS = $5456 ; TIOCSLCKTRMIOS = $5457 ; TIOCSERGSTRUCT = $5458 ; TIOCSERGETLSR = $5459 ; TIOCSERGETMULTI = $545A ; TIOCSERSETMULTI = $545B ; TIOCMIWAIT = $545C ; TIOCGICOUNT = $545D ; TIOCPKT_DATA = 0; TIOCPKT_FLUSHREAD = 1; TIOCPKT_FLUSHWRITE = 2; TIOCPKT_STOP = 4; TIOCPKT_START = 8; TIOCPKT_NOSTOP = 16; TIOCPKT_DOSTOP = 32; Other than that, all constants for setting the speed and control flags of a terminal line, as described in the termios (2) man page, are defined in the linux unit. It would take too much place to list them here. To check the mode field of a stat record, you ca use the following constants : { Constants to check stat.mode } STAT_IFMT = $f000; {00170000} STAT_IFSOCK = $c000; {0140000} STAT_IFLNK = $a000; {0120000} STAT_IFREG = $8000; {0100000} 138 8.2. FUNCTIONS AND PROCEDURES STAT_IFBLK = $6000; {0060000} STAT_IFDIR = $4000; {0040000} STAT_IFCHR = $2000; {0020000} STAT_IFIFO = $1000; {0010000} STAT_ISUID = $0800; {0004000} STAT_ISGID = $0400; {0002000} STAT_ISVTX = $0200; {0001000} { Constants to check permissions } STAT_IRWXO = $7; STAT_IROTH = $4; STAT_IWOTH = $2; STAT_IXOTH = $1; STAT_IRWXG = STAT_IRWXO shl 3; STAT_IRGRP = STAT_IROTH shl 3; STAT_IWGRP = STAT_IWOTH shl 3; STAT_IXGRP = STAT_IXOTH shl 3; STAT_IRWXU = STAT_IRWXO shl 6; STAT_IRUSR = STAT_IROTH shl 6; STAT_IWUSR = STAT_IWOTH shl 6; STAT_IXUSR = STAT_IXOTH shl 6; You can test the type of a filesystem returned by a FSStat (158) call with the following constants: fs_old_ext2 = $ef51; fs_ext2 = $ef53; fs_ext = $137d; fs_iso = $9660; fs_minix = $137f; fs_minix_30 = $138f; fs_minux_V2 = $2468; fs_msdos = $4d44; fs_nfs = $6969; fs_proc = $9fa0; fs_xia = $012FD16D; the FLock (157) call uses the following mode constants : LOCK_SH = 1; LOCK_EX = 2; LOCK_UN = 8; LOCK_NB = 4; 8.2 Functions and procedures Access Declaration: Function Access (Path : Pathstr; Mode : integer) : Boolean; Description: Tests user's access rights on the specified file. Mode is a mask existing of one or more of R OKUser has read rights. W OKUser has write rights. 139 8.2. FUNCTIONS AND PROCEDURES X OKUser has execute rights. F OKUser has search rights in the directory where the file is. The test is done with the real user ID, instead of the e ective user ID. If access is denied, or an error occurred, false is returned. Errors: LinuxError is used to report errors: sys eaccessThe requested access is denied, either to the file or one of the directo- ries in its path. sys einvalMode was incorrect. sys enoentA directory component in Path doesn't exist or is a dangling symbolic link. sys enotdirA directory component in Path is not a directory. sys enomemInsu cient kernel memory. sys eloopPath has a circular symbolic link. See also: Chown (143), Chmod (144), Access (2) Program Example26 ; { Program to demonstrate the Access f u n c t i o n . } Uses l i n u x ; begin i f Access ( '/ etc / passwd ' ,W OK) then begin Writeln ( ' Better check your system . ' ) ; Writeln ( ' I can w r i t e to the / etc / passwd f i l e ! ' ) ; end ; end . AssignPipe Declaration: Procedure AssignPipe (Pipe in, Pipe out : Text); Description: AssignePipe creates a pipe, i.e. two file objects, one for input, one for output. What is written to Pipe out, can be read from Pipe in. Reading and writing happens through the usual Readln(Pipe in,...) and Writeln (Pipe out,...) procedures. Errors: LinuxError is used to report errors: sys emfileToo many file descriptors for this process. sys enfileThe system file table is full. See also: POpen (177), MkFifo (175), pipe (2) Program Example36 ; { Program to demonstrate the AssignPipe f u n c t i o n . } Uses l i n u x ; 140 8.2. FUNCTIONS AND PROCEDURES Var p i p i , pipo : Text ; s : String ; begin Writeln ( ' A s s i g n i n g Pipes . ' ) ; a s s i g n p i p e ( p i p i , pipo ) ; i f l i n u x e r r o r <>0 then Writeln ( ' Error a s s i g n i n g pipes ! ' ) ; Writeln ( ' Writing to pipe , and f l u s h i n g . ' ) ; Writeln ( pipo , ' This i s a t e x t s t r i n g ' ) ; c l o s e ( pipo ) ; Writeln ( ' Reading from pipe . ' ) ; While not eof ( p i p i ) do begin Readln ( p i p i , s ) ; Writeln ( ' Read from pipe : ' , s ) ; end ; c l o s e ( p i p i ) ; writeln ( ' Closed pipes . ' ) ; writeln end . AssignStream Declaration: Procedure AssignStream (StreamIn,StreamOut : Text; Const prog : String); Description: AssignStream creates a 2 pipes, i.e. two file objects, one for input, one for output, the other ends of these pipes are connected to standard input and and output of Prog. Prog is the name of a program (including path) with options, which will be executed. What is written to StreamOut, will go to the standard input of Prog. Whatever is written by Prog to it's standard output be read from StreamIn. Read- ing and writing happens through the usual Readln(StreamIn,...) and Writeln (StreamOut,...) procedures. Remark: You should not use Reset or Rewrite on a file opened with POpen. This will close the file before re-opening it again, thereby closing the connection with the program. Errors: LinuxError is used to report errors: sys emfileToo many file descriptors for this process. sys enfileThe system file table is full. Other errors include the ones by the fork and exec programs See also: AssignPipe (140), POpen (177),pipe (2) Program Example38 ; { Program to demonstrate the AssignStream f u n c t i o n . } Uses l i n u x ; Var Si , So : Text ; S : String ; 141 8.2. FUNCTIONS AND PROCEDURES i : l o n g i n t ; begin i f not ( paramstr (1)= '- son ' ) then begin Writeln ( ' C a l l i n g son ' ) ; Assignstream ( Si , So , ' . / ex38 -son ' ) ; i f l i n u x e r r o r <>0 then begin writeln ( ' AssignStream f a i l e d ! ' ) ; halt ( 1 ) ; end ; Writeln ( ' Speaking to son ' ) ; For i :=1 to 10 do begin writeln ( so , ' Hello son ! ' ) ; i f i o r e s u l t <>0 then writeln ( ' Can ' ' t speak to son . . . ' ) ; end ; For i :=1 to 3 do writeln ( so , ' Hello chap ! ' ) ; c l o s e ( so ) ; while not eof ( s i ) do begin readln ( s i , s ) ; writeln ( ' Father : Son s aid : ' , S ) ; end ; Writeln ( ' Stopped c o n v e r s a t i o n ' ) ; Close ( Si ) ; Writeln ( ' Put down phone ' ) ; end Else begin Writeln ( ' This i s the son ' ) ; While not eof ( input ) do begin readln ( s ) ; i f pos ( ' Hello son ! ' , S)<>0 then Writeln ( ' Hello Dad ! ' ) elsewriteln ( 'Who are you ?' ); end ; c l o s e ( output ) ; end end . BaseName Declaration: Function BaseName (Const Path;Suf : Pathstr) : Pathstr; Description: Returns the filename part of Path, stripping o Suf if it exists. The filename part is the whole name if Path contains no slash, or the part of Path after the last slash. The last character of the result is not a slash, unless the directory is the root directory. Errors: None. 142 8.2. FUNCTIONS AND PROCEDURES See also: DirName (146), FExpand (157), Basename (1) Program Example48 ; { Program to demonstrate the BaseName f u n c t i o n . } Uses l i n u x ; Var S : String ; begin S:= FExpand ( Paramstr ( 0 ) ) ; Writeln ( ' This program i s c a l l e d : ' , Basename ( S , ' ' ) ) ; end . CFMakeRaw Declaration: Procedure CFMakeRaw (var Tios:TermIOS); Description: CFMakeRaw Sets the flags in the Termios structure Tios to a state so that the terminal will function in Raw Mode. Errors: None. See also: CFSetOSpeed (143), CFSetISpeed (143), termios (2) For an example, see TCGetAttr (186). CFSetISpeed Declaration: Procedure CFSetISpeed (var Tios:TermIOS;Speed:Longint); Description: CFSetISpeed Sets the input baudrate in the TermIOS structure Tios to Speed. Errors: None. See also: CFSetOSpeed (143), CFMakeRaw (143), termios (2) CFSetOSpeed Declaration: Procedure CFSetOSpeed (var Tios:TermIOS;Speed:Longint); Description: CFSetOSpeed Sets the output baudrate in the Termios structure Tios to Speed. Errors: None. See also: CFSetISpeed (143), CFMakeRaw (143), termios (2) Chown Declaration: Function Chown (Path : Pathstr;NewUid,NewGid : Longint) : Boolean; Description: Chown sets the User ID and Group ID of the file in Path to NewUid, NewGid. The function returns True if the call was succesfull, False if the call failed. 143 8.2. FUNCTIONS AND PROCEDURES Errors: Errors are returned in LinuxError. sys epermThe e ective UID doesn't match the ownership of the file, and is not zero. Owner or group were not specified correctly. sys eaccessOne of the directories in Path has no search (=execute) permission. sys enoentA directory entry in Path does not exist or is a symbolic link pointing to a non-existent directory. sys enotdirA directory entry in OldPath or NewPath is nor a directory. sys enomemInsu cient kernel memory. sys erofsThe file is on a read-only filesystem. sys eloopPath has a reference to a circular symbolic link, i.e. a symbolic link, whose expansion points to itself. See also: Chmod (144), Access (139), Chown (() 2) Program Example24 ; { Program to demonstrate the Chown f u n c t i o n . } Uses l i n u x ; Var UID , GID : Longint ; F : Text ; begin Writeln ( ' This w i l l only work i f you are root . ' ) ; Write ( ' Enter a UID : ' ) ; readln ( UID ) ; Write ( ' Enter a GID : ' ) ; readln ( GID ) ; Assign ( f , ' t e s t . txt ' ) ; Rewrite ( f ) ; Writeln ( f , ' The owner of t h i s f i l e should become : ' ) ; Writeln ( f , ' UID : ' , UID ) ; Writeln ( f , ' GID : ' , GID ) ; Close ( F ) ; i f not Chown ( ' t e s t . txt ' , UID , GID ) then i f L i n u x E r r o r =Sys EPERM then Writeln ( ' You are not root ! ' ) else Writeln ( ' Chmod f a i l e d with e x i t code : ' , L i n u x E r r o r ) else Writeln ( ' Changed owner s u c c e s s f u l l y ! ' ) ; end . Chmod Declaration: Function Chmod (Path : Pathstr;NewMode : Longint) : Boolean; Description: Chmod Sets the Mode bits of the file in Path to NewMode. Newmode can be specified by 'or'-ing the following: S ISUIDSet user ID on execution. 144 8.2. FUNCTIONS AND PROCEDURES S ISGIDSet Group ID on execution. S ISVTXSet sticky bit. S IRUSRRead by owner. S IWUSRWrite by owner. S IXUSRExecute by owner. S IRGRPRead by group. S IWGRPWrite by group. S IXGRPExecute by group. S IROTHRead by others. S IWOTHWrite by others. S IXOTHExecute by others. S IRWXORead, write, execute by others. S IRWXGRead, write, execute by groups. S IRWXURead, write, execute by user. Errors: Errors are returned in LinuxError. sys epermThe e ective UID doesn't match the ownership of the file, and is not zero. Owner or group were not specified correctly. sys eaccessOne of the directories in Path has no search (=execute) permission. sys enoentA directory entry in Path does not exist or is a symbolic link pointing to a non-existent directory. sys enotdirA directory entry in OldPath or NewPath is nor a directory. sys enomemInsu cient kernel memory. sys erofsThe file is on a read-only filesystem. sys eloopPath has a reference to a circular symbolic link, i.e. a symbolic link, whose expansion points to itself. See also: Chown (143), Access (139), Chmod (() 2) Program Example23 ; { Program to demonstrate the Chmod f u n c t i o n . } Uses l i n u x ; Var F : Text ; begin { Create a f i l e } Assign ( f , ' t e s t e x 2 1 ' ) ; Rewrite ( F ) ; Writeln ( f , '#!/ bin / sh ' ) ; Writeln ( f , ' echo Some text f o r t h i s f i l e ' ) ; Close ( F ) ; { Octal ( ) makes the c o r r e c t number from a number that LOOKS o c t a l } Chmod ( ' t e s t e x 2 1 ' , o c t a l ( 7 7 7 ) ) ; { F i l e i s now e x e c u t a b l e } e x e c l ( ' . / t e s t e x 2 1 ' ) ; end . 145 8.2. FUNCTIONS AND PROCEDURES CloseDir Declaration: Function CloseDir (p:pdir) : integer; Description: CloseDir closes the directory pointed to by p. It returns zero if the directory was closed succesfully, -1 otherwise. Errors: Errors are returned in LinuxError. See also: OpenDir (176), ReadDir (178), SeekDir (178), TellDir (188), closedir (3) For an example, see OpenDir (176). DirName Declaration: Function DirName (Const Path : Pathstr) : Pathstr; Description: Returns the directory part of Path. The directory is the part of Path before the last slash, or empty if there is no slash. The last character of the result is not a slash, unless the directory is the root directory. Errors: None. See also: BaseName (142), FExpand (157), Dirname (1) Program Example47 ; { Program to demonstrate the DirName f u n c t i o n . } Uses l i n u x ; Var S : String ; begin S:= FExpand ( Paramstr ( 0 ) ) ; Writeln ( ' This program i s in d i r e c t o r y : ' , Dirname ( S ) ) ; end . Dup Declaration: Procedure Dup (Var OldFile, NewFile : Text); Description: Makes NewFile an exact copy of OldFile, after having flushed the bu er of OldFile. Due to the bu ering mechanism of Pascal, this has not the same func- tionality as the dup (2) call in C. The internal Pascal bu ers are not the same after this call, but when the bu ers are flushed (e.g. after output), the output is sent to the same file. Doing an lseek will, however, work as in C, i.e. doing a lseek will change the fileposition in both files. Errors: Linuxerror is used to report errors. sys ebadfOldFile hasn't been assigned. sys emfileMaximum number of open files for the process is reached. See also: Dup2 (147), Dup (2) 146 8.2. FUNCTIONS AND PROCEDURES program Example31 ; { Program to demonstrate the Dup f u n c t i o n . } uses l i n u x ; var f : text ; begin i f not dup ( output , f ) then Writeln ( ' Dup F a i l e d ! ' ) ; writeln ( ' This i s w r i t t e n to stdout . ' ) ; writeln ( f , ' This i s w r i t t e n to the dup f i l e , and f l u s h e d ' ) ; flush ( f ) ; writeln end . Dup2 Declaration: Procedure Dup2 (Var OldFile, NewFile : Text); Description: Makes NewFile an exact copy of OldFile, after having flushed the bu er of OldFile. NewFile can be an assigned file. If newfile was open, it is closed first. Due to the bu ering mechanism of Pascal, this has not the same functionality as the dup2 (2) call in C. The internal Pascal bu ers are not the same after this call, but when the bu ers are flushed (e.g. after output), the output is sent to the same file. Doing an lseek will, however, work as in C, i.e. doing a lseek will change the fileposition in both files. Errors: Linuxerror is used to report errors. sys ebadfOldFile hasn't been assigned. sys emfileMaximum number of open files for the process is reached. See also: Dup (146), Dup2 (2) program Example31 ; { Program to demonstrate the Dup f u n c t i o n . } uses l i n u x ; var f : text ; i : l o n g i n t ; begin Assign ( f , ' text . txt ' ) ; Rewrite ( F ) ; For i :=1 to 10 do writeln ( F, ' Line : ' , i ) ; i f not dup2 ( output , f ) then Writeln ( ' Dup2 F a i l e d ! ' ) ; writeln ( ' This i s w r i t t e n to stdout . ' ) ; writeln ( f , ' This i s w r i t t e n to the dup f i l e , and f l u s h e d ' ) ; flush ( f ) ; writeln ; 147 8.2. FUNCTIONS AND PROCEDURES { Remove f i l e . Comment t h i s i f you want to check f l u s h i n g .} Unlink ( ' text . txt ' ) ; end . EpochToLocal Declaration: Procedure EpochToLocal (Epoch : Longint; var Year,Month,Day,Hour,Minute,Second : Word); Description: Converts the epoch time (=Number of seconds since 00:00:00 , January 1, 1970, corrected for your time zone ) to local date and time. Errors: None See also: GetEpochTime (163), LocalToEpoch (174), GetTime (166),GetDate (161) Program Example3 ; { Program to demonstrate the EpochToLocal f u n c t i o n . } Uses l i n u x ; Var Year , month , day , hour , minute , seconds : Word ; begin EpochToLocal ( GetEpochTime , Year , month , day , hour , minute , seconds ) ; Writeln ( ' Current date : ' , Day : 2 , ' / ' , Month : 2 , ' / ' , Year : 4 ) ; Writeln ( ' Current time : ' , Hour : 2 , ' : ' , minute : 2 , ' : ' , seconds : 2 ) ; end . Execl Declaration: Procedure Execl (Path : pathstr); Description: Replaces the currently running program with the program, specified in path. Path is split into a command and it's options. The executable in path is NOT searched in the path. The current environment is passed to the program. On success, execl does not return. Errors: Errors are reported in LinuxError: sys eaccesFile is not a regular file, or has no execute permission. A compononent of the path has no search permission. sys epermThe file system is mounted noexec. sys e2bigArgument list too big. sys enoexecThe magic number in the file is incorrect. sys enoentThe file does not exist. sys enomemNot enough memory for kernel, or to split command line. sys enotdirA component of the path is not a directory. sys eloopThe path contains a circular reference (via symlinks). See also: Execve (151), Execv (150), Execvp (152), Execle (149), Execlp (150), Fork (161), execvp (3) 148 8.2. FUNCTIONS AND PROCEDURES Program Example10 ; { Program to demonstrate the Execl f u n c t i o n . } Uses l i n u x , s t r i n g s ; begin { Execute ' l s - l ' , with c u r r e n t environment . } { ' l s ' i s NOT looked f or in PATH environment v a r i a b l e .} Execl ( '/ bin / l s -l ' ) ; end . Execle Declaration: Procedure Execle (Path : pathstr, Ep : ppchar); Description: Replaces the currently running program with the program, specified in path. Path is split into a command and it's options. The executable in path is searched in the path, if it isn't an absolute filename. The environment in ep is passed to the program. On success, execle does not return. Errors: Errors are reported in LinuxError: sys eaccesFile is not a regular file, or has no execute permission. A compononent of the path has no search permission. sys epermThe file system is mounted noexec. sys e2bigArgument list too big. sys enoexecThe magic number in the file is incorrect. sys enoentThe file does not exist. sys enomemNot enough memory for kernel, or to split command line. sys enotdirA component of the path is not a directory. sys eloopThe path contains a circular reference (via symlinks). See also: Execve (151), Execv (150), Execvp (152), Execl (148), Execlp (150), Fork (161), execvp (3) Program Example11 ; { Program to demonstrate the Execle f u n c t i o n . } Uses l i n u x , s t r i n g s ; begin { Execute ' l s - l ' , with c u r r e n t environment . } { ' l s ' i s NOT looked f o r in PATH environment v a r i a b l e .} { envp i s d e f i n e d in the system unit .} Execle ( '/ bin / l s -l ' , envp ) ; end . 149 8.2. FUNCTIONS AND PROCEDURES Execlp Declaration: Procedure Execlp (Path : pathstr); Description: Replaces the currently running program with the program, specified in path. Path is split into a command and it's options. The executable in path is searched in the path, if it isn't an absolute filename. The current environment is passed to the program. On success, execlp does not return. Errors: Errors are reported in LinuxError: sys eaccesFile is not a regular file, or has no execute permission. A compononent of the path has no search permission. sys epermThe file system is mounted noexec. sys e2bigArgument list too big. sys enoexecThe magic number in the file is incorrect. sys enoentThe file does not exist. sys enomemNot enough memory for kernel, or to split command line. sys enotdirA component of the path is not a directory. sys eloopThe path contains a circular reference (via symlinks). See also: Execve (151), Execv (150), Execvp (152), Execle (149), Execl (148), Fork (161), execvp (3) Program Example12 ; { Program to demonstrate the Execlp f u n c t i o n . } Uses l i n u x , s t r i n g s ; begin { Execute ' l s - l ' , with c u r r e n t environment . } { ' l s ' i s looked fo r in PATH environment v a r i a b l e .} { envp i s d e f i n e d in the system unit .} Execlp ( ' l s -l ' , envp ) ; end . Execv Declaration: Procedure Execv (Path : pathstr; args : ppchar); Description: Replaces the currently running program with the program, specified in path. It gives the program the options in args. This is a pointer to an array of pointers to null-terminated strings. The last pointer in this array should be nil. The current environment is passed to the program. On success, execv does not return. Errors: Errors are reported in LinuxError: sys eaccesFile is not a regular file, or has no execute permission. A compononent of the path has no search permission. sys epermThe file system is mounted noexec. sys e2bigArgument list too big. sys enoexecThe magic number in the file is incorrect. 150 8.2. FUNCTIONS AND PROCEDURES sys enoentThe file does not exist. sys enomemNot enough memory for kernel. sys enotdirA component of the path is not a directory. sys eloopThe path contains a circular reference (via symlinks). See also: Execve (151), Execvp (152), Execle (149), Execl (148), Execlp (150), Fork (161), execv (3) Program Example8 ; { Program to demonstrate the Execv f u n c t i o n . } Uses l i n u x , s t r i n g s ; Const Arg0 : PChar = '/ bin / l s ' ; Arg1 : Pchar = '- l ' ; Var PP : PPchar ; begin GetMem ( PP,3 SizeOf ( Pchar ) ) ; PP[0]:= Arg0 ; PP[1]:= Arg1 ; PP[3]:= Nil ; { Execute '/ bin / l s - l ' , with c u r r e n t environment } Execv ( '/ bin / l s ' , pp ) ; end . Execve Declaration: Procedure Execve (Path : pathstr; args,ep : ppchar); Description: Replaces the currently running program with the program, specified in path. It gives the program the options in args, and the environment in ep. They are pointers to an array of pointers to null-terminated strings. The last pointer in this array should be nil. On success, execve does not return. Errors: Errors are reported in LinuxError: eaccesFile is not a regular file, or has no execute permission. A compononent of the path has no search permission. sys epermThe file system is mounted noexec. sys e2bigArgument list too big. sys enoexecThe magic number in the file is incorrect. sys enoentThe file does not exist. sys enomemNot enough memory for kernel. sys enotdirA component of the path is not a directory. sys eloopThe path contains a circular reference (via symlinks). See also: Execve (151), Execv (150), Execvp (152) Execle (149), Execl (148), Execlp (150), Fork (161), execve (2) 151 8.2. FUNCTIONS AND PROCEDURES Program Example7 ; { Program to demonstrate the Execve f u n c t i o n . } Uses l i n u x , s t r i n g s ; Const Arg0 : PChar = '/ bin / l s ' ; Arg1 : Pchar = '- l ' ; Var PP : PPchar ; begin GetMem ( PP,3 SizeOf ( Pchar ) ) ; PP[0]:= Arg0 ; PP[1]:= Arg1 ; PP[3]:= Nil ; { Execute '/ bin / l s - l ' , with c u r r e n t environment } { Envp i s d e f i n e d in system . inc } ExecVe ( '/ bin / l s ' , pp , envp ) ; end . Execvp Declaration: Procedure Execvp (Path : pathstr; args : ppchar); Description: Replaces the currently running program with the program, specified in path. The executable in path is searched in the path, if it isn't an absolute filename. It gives the program the options in args. This is a pointer to an array of pointers to null-terminated strings. The last pointer in this array should be nil. The current environment is passed to the program. On success, execvp does not return. Errors: Errors are reported in LinuxError: sys eaccesFile is not a regular file, or has no execute permission. A compononent of the path has no search permission. sys epermThe file system is mounted noexec. sys e2bigArgument list too big. sys enoexecThe magic number in the file is incorrect. sys enoentThe file does not exist. sys enomemNot enough memory for kernel. sys enotdirA component of the path is not a directory. sys eloopThe path contains a circular reference (via symlinks). See also: Execve (151), Execv (150), Execle (149), Execl (148), Execlp (150), Fork (161), execvp (3) Program Example9 ; { Program to demonstrate the Execvp f u n c t i o n . } Uses l i n u x , s t r i n g s ; 152 8.2. FUNCTIONS AND PROCEDURES Const Arg0 : PChar = ' l s ' ; Arg1 : Pchar = '- l ' ; Var PP : PPchar ; begin GetMem ( PP,3 SizeOf ( Pchar ) ) ; PP[0]:= Arg0 ; PP[1]:= Arg1 ; PP[3]:= Nil ; { Execute ' l s - l ' , with c u r r e n t environment . } { ' l s ' i s looked fo r in PATH environment v a r i a b l e .} { Envp i s d e f i n e d in the system unit . } Execvp ( ' l s ' , pp , envp ) ; end . FD ZERO Declaration: Procedure FD ZERO (var fds:fdSet); Description: FD ZERO clears all the filedescriptors in the file descriptor set fds. Errors: None. See also: Select (178), SelectText (180), GetFS (164), FD Clr (153), FD Set (154), FD IsSet (153) For an example, see Select (178). FD Clr Declaration: Procedure FD Clr (fd:longint;var fds:fdSet); Description: FD Clr clears file descriptor fd in filedescriptor s et fds. Errors: None. See also: Select (178), SelectText (180), GetFS (164), FD ZERO (153), FD Set (154), FD IsSet (153) For an example, see Select (178). FD IsSet Declaration: Function FD IsSet (fd:longint;var fds:fdSet) : boolean; Description: FD Set Checks whether file descriptor fd in filedescriptor set fds is set. Errors: None. See also: Select (178), SelectText (180), GetFS (164), FD ZERO (153), FD Clr (153), FD Set (154) For an example, see Select (178). 153 8.2. FUNCTIONS AND PROCEDURES FD Set Declaration: Procedure FD Set (fd:longint;var fds:fdSet); Description: FD Set sets file descriptor fd in filedescriptor set fds. Errors: None. See also: Select (178), SelectText (180), GetFS (164),FD ZERO (153), FD Clr (153), FD IsSet (153) For an example, see Select (178). fdClose Declaration: Function fdClose (fd:longint) : boolean; Description: fdClose closes a file with file descriptor Fd. The function returns True if the file was closed successfully, False otherwise. Errors: Errors are returned in LinuxError See also: fdOpen (154), fdRead (155), fdWrite (157),fdTruncate (156), fdFlush (154), seefFd- Seek For an example, see fdOpen (154). fdFlush Declaration: Function fdFlush (fd:Longint) : boolean; Description: fdflush flushes the Linux kernel file bu er, so the file is actually written to disk. This is NOT the same as the internal bu er, maintained by Free Pascal. The function returns True if the call was successful, false if an error occurred. Errors: Errors are returned in LinuxError. See also: fdOpen (154), fdClose (154), fdRead (155),fdWrite (157), fdTruncate (156), fdSeek (156) For an example, see fdRead (155). fdOpen Declaration: Function fdOpen (Var PathName;flags:longint[; Mode: longint]) : longint; Description: fdOpen opens a file in pathname with flags flags a ORed combination of Open Accmode, Open RdOnly, Open WrOnly, Open RdWr, Open Creat, Open Excl, Open NoCtty, Open Trunc, Open Append, Open NonBlock, Open NDelay, Open Sync PathName can be of type PChar or String The optional mode argument specifies the permis- sions to set when opening the file. This is modified by the umask setting. The real permissions are Mode and not umask. The return value of the function is the filedescriptor, or a negative value if there was an error. Errors: Errors are returned in LinuxError 154 8.2. FUNCTIONS AND PROCEDURES See also: fdClose (154), fdRead (155), fdWrite (157),fdTruncate (156), fdFlush (154), fdSeek (156) Program Example19 ; { Program to demonstrate the fdOpen , f d w r i t e and fdCLose f u n c t i o n s . } Uses l i n u x ; Const Line : String [ 8 0 ] = ' This i s easy w r i t i n g ! ' ; Var FD : Longint ; begin FD:= fdOpen ( ' Test . dat ' , Open WrOnly or Open Creat ) ; i f FD>0 then begin i f length ( Line )<>f d w r i t e ( FD, Line [ 1 ] , Length ( Line ) ) then Writeln ( ' Error when w r i t i n g to f i l e ! ' ) ; f d C l o s e (FD) ; end ; end . fdRead Declaration: Function fdRead (fd:longint;var buf;size:longint : longint; Description: fdRead reads at most size bytes from the file descriptor fd, and stores them in buf. The function returns the number of bytes actually read, or -1 if an error occurred. No checking on the length of buf is done. Errors: Errors are returned in LinuxError. See also: fdOpen (154), fdClose (154), fdWrite (157),fdTruncate (156), fdFlush (154), fdSeek (156) Program Example20 ; { Program to demonstrate the fdRead and fdTruncate f u n c t i o n s . } Uses l i n u x ; Const Data : st r ing [ 1 0 ] = '12345687890' ; Var FD : Longint ; l : l o n g i n t ; begin FD:= fdOpen ( ' t e s t . dat ' , open wronly or open creat , o c t a l ( 6 6 6 ) ) ; i f fd >0 then begin { F i l l f i l e with data } for l :=1 to 10 do i f fdWrite ( FD, Data [1],10)<>10 then 155 8.2. FUNCTIONS AND PROCEDURES begin writeln ( ' Error when w r i t i n g ! ' ) ; halt ( 1 ) ; end ; f d C l o s e (FD) ; FD:= fdOpen ( ' t e s t . dat ' , open rdonly ) ; { Read data again } I f FD>0 then begin For l :=1 to 5 do i f fdRead ( FD, Data [1],10)<>10 then begin Writeln ( ' Error when Reading ! ' ) ; Halt ( 2 ) ; end ; fdCLose (FD) ; { Truncating f i l e at 60 bytes } { For t r u n c a t i n g , f i l e must be open or w r i t e } FD:= fdOpen ( ' t e s t . dat ' , open wronly , o c t a l ( 6 6 6 ) ) ; i f FD>0 then begin i f not fdTruncate (FD, 6 0 ) then Writeln ( ' Error when t r u n c a t i n g ! ' ) ; f d C l o s e ( FD) ; end ; end ; end ; end . fdSeek Declaration: Function fdSeek (fd,Pos,SeekType:longint : longint; Description: fdSeek sets the current fileposition of file fd to Pos, starting from SeekType, which can be one of the following: Seek Set Pos is the absolute position in the file. Seek Cur Pos is relative to the current position. Seek end Pos is relative to the end of the file. The function returns the new fileposition, or -1 of an error occurred. Errors: Errors are returned in LinuxError. See also: fdOpen (154), fdWrite (157), fdClose (154), fdRead (155),fdTruncate (156), fdFlush (154) For an example, see fdOpen (154). fdTruncate Declaration: Function fdTruncate (fd,size:longint) : boolean; 156 8.2. FUNCTIONS AND PROCEDURES Description: fdTruncate sets the length of a file in fd on size bytes, where size must be less than or equal to the current length of the file in fd. The function returns True if the call was successful, false if an error occurred. Errors: Errors are returned in LinuxError. See also: fdOpen (154), fdClose (154), fdRead (155),fdWrite (157),fdFlush (154), fdSeek (156) fdWrite Declaration: Function fdWrite (fd:longint;var buf;size:longint : longint; Description: fdWrite writes at most size bytes from buf to file descriptor fd. The function returns the number of bytes actually written, or -1 if an error occurred. Errors: Errors are returned in LinuxError. See also: fdOpen (154), fdClose (154), fdRead (155),fdTruncate (156), fdSeek (156), fdFlush (154) FExpand Declaration: Function FExpand (Const Path: Pathstr) : pathstr; Description: Expands Path to a full path, starting from root, eliminating directory references such as . and .. from the result. Errors: None See also: BaseName (142),DirName (146) Program Example45 ; { Program to demonstrate the FExpand f u n c t i o n . } Uses l i n u x ; begin Writeln ( ' This program i s in : ' , FExpand ( Paramstr ( 0 ) ) ) ; end . FLock Declaration: Procedure FLock (Var F; Mode : longint); Description: FLock implements file locking. it sets or removes a lock on the file F. F can be of type Text or File, or it can be a linux filedescriptor (a longint) Mode can be one of the following constants : LOCK SH sets a shared lock. LOCK EX sets an exclusive lock. LOCK UN unlocks the file. LOCK NB This can be OR-ed together with the other. If this is done the appli- cation doesn't block when locking. Errors: Errors are reported in LinuxError. See also: Fcntl (160), flock (2) 157 8.2. FUNCTIONS AND PROCEDURES FSStat Declaration: Function FSStat (Path : Pathstr; Var Info : statfs) : Boolean; Description: Return in Info information about the filesystem on which the file Path resides. Info is of type statfs. The function returns True if the call was succesfull, False if the call failed. Errors: LinuxError is used to report errors. sys enotdirA component of Path is not a directory. sys einvalInvalid character in Path. sys enoentPath does not exist. sys eaccessSearch permission is denied for component in Path. sys eloopA circular symbolic link was encountered in Path. sys eioAn error occurred while reading from the filesystem. See also: FStat (159), LStat (172), statfs (2) program Example30 ; { Program to demonstrate the FSStat f u n c t i o n . } uses l i n u x ; var s : st r ing ; i n f o : s t a t f s ; begin writeln ( ' I n f o about c u r r e n t p a r t i t i o n : ' ) ; s := ' . ' ; while s<>' q ' do begin i f not f s s t a t ( s , i n f o ) then begin writeln ( ' Fstat f a i l e d . Errno : ' , l i n u x e r r o r ) ; halt ( 1 ) ; end ; writeln ; writeln ( ' Result of f s s t a t on f i l e ' ' ' , s , ' ' ' . ' ) ; writeln ( ' f s t y p e : ' , i n f o . f s t y p e ) ; writeln ( ' b s i z e : ' , i n f o . b s i z e ) ; writeln ( ' b f r e e : ' , i n f o . b f r e e ) ; writeln ( ' b a v a i l : ' , i n f o . b a v a i l ) ; writeln ( ' f i l e s : ' , i n f o . f i l e s ) ; writeln ( ' f f r e e : ' , i n f o . f f r e e ) ; writeln ( ' f s i d : ' , i n f o . f s i d ) ; writeln ( ' Namelen : ' , i n f o . namelen ) ; write ( ' Type name of f i l e to do f s s t a t . ( q q u i t s ) : ' ) ; readln ( s ) end ; end . 158 8.2. FUNCTIONS AND PROCEDURES FSearch Declaration: Function FSearch (Path : pathstr;DirList : string) : Pathstr; Description: Searches in DirList, a colon separated list of directories, for a file named Path. It then returns a path to the found file. Errors: An empty string if no such file was found. See also: BaseName (142), DirName (146), FExpand (157) Program Example46 ; { Program to demonstrate the FSearch f u n c t i o n . } Uses l i n u x , s t r i n g s ; begin Writeln ( ' l s i s in : ' , FSearch ( ' l s ' , strpas ( Getenv ( ' PATH' ) ) ) ) ; end . FStat Declaration: Function FStat (Path : Pathstr; Var Info : stat) : Boolean; Description: FStat gets information about the file specified in Path, and stores it in Info, which is of type stat. The function returns True if the call was succesfull, False if the call failed. Errors: LinuxError is used to report errors. sys enoentPath does not exist. See also: FSStat (158), LStat (172), stat (2) program example28 ; { Program to demonstrate the FStat f u n c t i o n . } uses l i n u x ; var f : text ; i : byte ; i n f o : s t a t ; begin { Make a f i l e } a s s i g n ( f , ' t e s t . f i l ' ) ; rewrite ( f ) ; for i :=1 to 10 do writeln ( f , ' T e s t l i n e # ' , i ) ; c l o s e ( f ) ; { Do the c a l l on made f i l e . } i f not f s t a t ( ' t e s t . f i l ' , i n f o ) then begin writeln ( ' Fstat f a i l e d . Errno : ' , l i n u x e r r o r ) ; halt ( 1 ) ; 159 8.2. FUNCTIONS AND PROCEDURES end ; writeln ; writeln ( ' Result of f s t a t on f i l e ' ' t e s t . f i l ' ' . ' ) ; writeln ( ' Inode : ' , i n f o . ino ) ; writeln ( ' Mode : ' , i n f o . mode ) ; writeln ( ' n l i n k : ' , i n f o . n l i n k ) ; writeln ( ' uid : ' , i n f o . uid ) ; writeln ( ' gid : ' , i n f o . gid ) ; writeln ( ' rdev : ' , i n f o . rdev ) ; writeln ( ' Size : ' , i n f o . s i z e ) ; writeln ( ' B l k s i z e : ' , i n f o . b l k s z e ) ; writeln ( ' Blocks : ' , i n f o . blocks ) ; writeln ( ' atime : ' , i n f o . atime ) ; writeln ( ' mtime : ' , i n f o . mtime ) ; writeln ( ' ctime : ' , i n f o . ctime ) ; { Remove f i l e } erase ( f ) ; end . Fcntl Declaration: Function Fcntl (Fd : text, Cmd : Integer) : Integer; Description: Read a file's attributes. Fd is an assigned file. Cmd speciefies what to do, and is one of the following: F GetFdRead the close on exec flag. If the low-order bit is 0, then the file will remain open across execve calls. F GetFlRead the descriptor's flags. F GetOwnGet the Process ID of the owner of a socket. Errors: LinuxError is used to report errors. sys ebadfFd has a bad file descriptor. See also: Fcntl (160), Fcntl (2) Fcntl Declaration: Procedure Fcntl (Fd : text, Cmd : Integer; Arg : longint); Description: Read or Set a file's attributes. Fd is an assigned file. Cmd speciefies what to do, and is one of the following: F SetFdSet the close on exec flag of Fd. (only the least siginificant bit is used). F GetLkReturn the flock record that prevents this process from obtaining the lock, or set the l type field of the lock of there is no obstruction. Arg is a pointer to a flock record. F SetLkSet the lock or clear it (depending on l type in the flock structure). if the lock is held by another process, an error occurs. F GetLkwSame as for F Setlk, but wait until the lock is released. F SetOwnSet the Process or process group that owns a socket. Errors: LinuxError is used to report errors. 160 8.2. FUNCTIONS AND PROCEDURES sys ebadfFd has a bad file descriptor. sys eagain or sys eaccessFor F SetLk, if the lock is held by another process. See also: Fcntl (160), Fcntl (2) Fork Declaration: Function Fork : Longint; Description: Fork creates a child process which is a copy of the parent process. Fork returns the process ID in the parent process, and zero in the child's process. (you can get the parent's PID with GetPPid (166)). Errors: On error, -1 is returned to the parent, and no child is created. sys eagainNot enough memory to create child process. See also: Execve (151), fork (2) Program Example14 ; { Program to demonstrate the Fork and WaitPidfunction . } Uses l i n u x ; Var PID , E x i t S t a t u s : Longint ; begin Writeln ( ' Spawning a c h i l d ' ) ; PID:= Fork ; I f PID=0 then begin Writeln ( ' Hello From the Child ! ! ' ) ; Writeln ( ' E x i t i n g with e x i t s t a t u s 1 ! ' ) ; Halt ( 1 ) ; end Else begin Writeln ( ' Spawned c h i l d with PID : ' , PID ) ; WaitPid ( PID , @ExitStatus , 0 ) ; Writeln ( ' Child e x i t e d with s t a t u s : ' , E x i t S t a t u s shr 8 ) ; end ; end . GetDate Declaration: Procedure GetDate (Var Year, Month, Day : Word) ; Description: Returns the current day. Errors: None See also: GetEpochTime (163), GetTime (166), EpochToLocal (148) 161 8.2. FUNCTIONS AND PROCEDURES Program Example6 ; { Program to demonstrate the GetDate f u n c t i o n . } Uses l i n u x ; Var Year , Month , Day : Word ; begin GetDate ( Year , Month , Day ) ; Writeln ( ' Date : ' , Day : 2 , ' / ' , Month : 2 , ' / ' , Year : 4 ) ; end . GetDomainName Declaration: Function GetDomainName : String; Description: Get the domain name of the machine on which the process is running. An empty string is returned if the domain is not set. Errors: None. See also: GetHostName (165),seemGetdomainname2 Program Example39 ; { Program to demonstrate the GetDomainName f u n c t i o n . } Uses l i n u x ; begin Writeln ( ' Domain name of t h i s machine i s : ' , GetDomainName ) ; end . GetEGid Declaration: Function GetEGid : Longint; Description: Get the e ective group ID of the currently running process. Errors: None. See also: GetGid (164), getegid (2) Program Example18 ; { Program to demonstrate the GetGid and GetEGid f u n c t i o n s . } Uses l i n u x ; begin writeln ( ' Group Id = ' , get gid , ' E f f e c t i v e group Id = ' , g e t e g i d ) ; end . 162 8.2. FUNCTIONS AND PROCEDURES GetEUid Declaration: Function GetEUid : Longint; Description: Get the e ective user ID of the currently running process. Errors: None. See also: GetEUid (163), geteuid (2) Program Example17 ; { Program to demonstrate the GetUid and GetEUid f u n c t i o n s . } Uses l i n u x ; begin writeln ( ' User Id = ' , getuid , ' E f f e c t i v e user Id = ' , g e t eu i d ) ; end . GetEnv Declaration: Function GetEnv (P : String) : PChar; Description: Returns the value of the environment variable in P. If the variable is not defined, nil is returned. The value of the environment variable may be the empty string. A PChar is returned to accomodate for strings longer than 255 bytes, TERMCAP and LS COLORS, for instance. Errors: None. See also: sh (1) , csh (1) Program Example41 ; { Program to demonstrate the GetEnv f u n c t i o n . } Uses l i n u x ; begin Writeln ( ' Path i s : ' , Getenv ( ' PATH' ) ) ; end . GetEpochTime Declaration: Function GetEpochTime : longint; Description: returns the number of seconds since 00:00:00 gmt, january 1, 1970. it is adjusted to the local time zone, but not to DST. Errors: no errors See also: EpochToLocal (148), GetTime (166), time (2) 163 8.2. FUNCTIONS AND PROCEDURES Program Example1 ; { Program to demonstrate the GetEpochTime f u n c t i o n . } Uses l i n u x ; begin Write ( ' Secs past the s t a r t of the Epoch ( 0 0 : 0 0 1 / 1 / 1 9 8 0 ) : ' ) ; Writeln ( GetEpochTime ) ; end . GetFS Declaration: Function GetFS (Var F : Any File Type) : Longint; Description: GetFS returns the file selector that the kernel provided for your file. In principle you don' need this file selector. Only for some calls it is needed, such as the Select (178) call or so. Errors: In case the file was not opened, then -1 is returned. See also: Select (178) Program Example33 ; { Program to demonstrate the S e le ct T ext f u n c t i o n . } Uses l i n u x ; Var tv : TimeVal ; begin Writeln ( ' Press the to continue the program . ' ) ; { Wait u n t i l F i l e d e s c r i p t o r 0 (= Input ) changes } S e l e ct T e x t ( Input , n i l ) ; { Get r i d of in b u f f e r } readln ; Writeln ( ' Press key in l e s s than 2 seconds . . . ' ) ; tv . sec :=2; tv . usec :=0; i f S e l e c t T e x t ( Input , @tv )>0 then Writeln ( ' Thank you ! ' ) else Writeln ( ' Too l a t e ! ' ) ; end . GetGid Declaration: Function GetGid : Longint; Description: Get the real group ID of the currently running process. Errors: None. See also: GetEGid (162), getgid (2) 164 8.2. FUNCTIONS AND PROCEDURES Program Example18 ; { Program to demonstrate the GetGid and GetEGid f u n c t i o n s . } Uses l i n u x ; begin writeln ( ' Group Id = ' , g et gi d , ' E f f e c t i v e group Id = ' , g e t e g i d ) ; end . GetHostName Declaration: Function GetHostName : String; Description: Get the hostname of the machine on which the process is running. An empty string is returned if hostname is not set. Errors: None. See also: GetDomainName (162),seemGethostname2 Program Example40 ; { Program to demonstrate the GetHostName f u n c t i o n . } Uses l i n u x ; begin Writeln ( ' Name of t h i s machine i s : ' , GetHostName ) ; end . GetPid Declaration: Function GetPid : Longint; Description: Get the Process ID of the currently running process. Errors: None. See also: GetPPid (166), getpid (2) Program Example16 ; { Program to demonstrate the GetPid , GetPPid f u n c t i o n . } Uses l i n u x ; begin Writeln ( ' Process Id = ' , getpid , ' Parent p r o c e s s Id = ' , getppid ) ; end . 165 8.2. FUNCTIONS AND PROCEDURES GetPPid Declaration: Function GetPPid : Longint; Description: Get the Process ID of the parent process. Errors: None. See also: GetPid (165), getppid (2) Program Example16 ; { Program to demonstrate the GetPid , GetPPid f u n c t i o n . } Uses l i n u x ; begin Writeln ( ' Process Id = ' , getpid , ' Parent p r o c e s s Id = ' , getppid ) ; end . GetPriority Declaration: Function GetPriority (Which,Who : Integer) : Integer; Description: GetPriority returns the priority with which a process is running. Which process(es) is determined by the Which and Who variables. Which can be one of the pre-defined Prio Process, Prio PGrp, Prio User, in which case Who is the process ID, Process group ID or User ID, respectively. Errors: Error checking must be done on LinuxError, since a priority can be negative. sys esrchNo process found using which and who. sys einvalWhich was not one of Prio Process, Prio Grp or Prio User. See also: SetPriority (180), Nice (175), Getpriority (2) For an example, see Nice (175). GetTime Declaration: Procedure GetTime (Var Hour,Minute, Second : Word) ; Description: Returns the current time of the day. Errors: None See also: GetEpochTime (163), GetDate (161), EpochToLocal (148) Program Example5 ; { Program to demonstrate the GetTime f u n c t i o n . } Uses l i n u x ; Var Hour , Minute , Second : Word ; 166 8.2. FUNCTIONS AND PROCEDURES begin GetTime ( Hour , Minute , Second ) ; Writeln ( ' Time : ' , Hour : 2 , ' : ' , Minute : 2 , ' : ' , Second : 2 ) ; end . GetUid Declaration: Function GetUid : Longint; Description: Get the real user ID of the currently running process. Errors: None. See also: GetEUid (163), getuid (2) Program Example17 ; { Program to demonstrate the GetUid and GetEUid f u n c t i o n s . } Uses l i n u x ; begin writeln ( ' User Id = ' , getuid , ' E f f e c t i v e user Id = ' , g e t eu i d ) ; end . Glob Declaration: Function Glob (Const Path : Pathstr) : PGlob; Description: Glob returns a pointer to a glob structure which contains all filenames which exist and match the pattern in Path. The pattern can contain wildcard characters, which have their usual meaning. Errors: Returns nil on error, and LinuxError is set. sys enomemNo memory on heap for glob structure. othersAs returned by the opendir call, and sys readdir. See also: GlobFree (168), Glob (3) Program Example49 ; { Program to demonstrate the Glob and GlobFree f u n c t i o n s . } Uses l i n u x ; Var G1 , G2 : PGlob ; begin G1:= Glob ( ' ' ) ; i f L i n u x E r r o r =0 then begin G2:=G1 ; Writeln ( ' F i l e s in t h i s d i r e c t o r y : ' ) ; 167 8.2. FUNCTIONS AND PROCEDURES While g2<>Nil do begin Writeln ( g2 . name) ; g2 :=g2 . next ; end ; GlobFree ( g1 ) ; end ; end . GlobFree Declaration: Procedure GlobFree (Var P : Pglob); Description: Releases the memory, occupied by a pglob structure. P is set to nil. Errors: None See also: Glob (167) For an example, see Glob (167). IOCtl Declaration: Procedure IOCtl (Handle,Ndx: Longint; Data: Pointer); Description: This is a general interface to the Unix/ linux ioctl call. It performs various operations on the filedescriptor Handle. Ndx describes the operation to perform. Data points to data needed for the Ndx function. The structure of this data is function-dependent, so we don't elaborate on this here. For more information on this, see various manual pages under linux. Errors: Errors are reported in LinuxError. They are very dependent on the used function, that's why we don't list them here See also: ioctl (2) Program Example54 ; uses Linux ; { Program to demonstrate the IOCtl f u n c t i o n . } vartios : Termios ; begin IOCtl (1, TCGETS, @tios ) ; WriteLn ( ' Input Flags : $ ' , h e x s t r ( t i o s . c i f l a g , 8 ) ) ; WriteLn ( ' Output Flags : $ ' , h e x s t r ( t i o s . c oflag , 8 ) ) ; WriteLn ( ' Line Flags : $ ' , h e x s t r ( t i o s . c l f l a g , 8 ) ) ; WriteLn ( ' Control Flags : $ ' , h e x s t r ( t i o s . c cflag , 8 ) ) ; end . 168 8.2. FUNCTIONS AND PROCEDURES IOperm Declaration: Function IOperm (From,Num : Cadinal; Value : Longint) : boolean; Description: IOperm sets permissions on Num ports starting with port From to Value. The function returns True if the call was successfull, False otherwise. Remark: *This works ONLY as root. *Only the first 0x03ff ports can be set. *When doing a Fork (161), the permissions are reset. When doing a Execve (151) they are kept. Errors: Errors are returned in LinuxError See also: ioperm (2) IsATTY Declaration: Function IsATTY (var f) : Boolean; Description: Check if the filehandle described by f is a terminal. f can be of type 1.longint for file handles; 2.Text for text variables such as input etc. Returns True if f is a terminal, False otherwise. Errors: No errors are reported See also: IOCtl (168),TTYName (187) S ISBLK Declaration: Function S ISBLK (m:integer) : boolean; Description: S ISBLK checks the file mode m to see whether the file is a block device file. If so it returns True. Errors: FStat (159), S ISLNK (170), S ISREG (171), S ISDIR (170), S ISCHR (169), S ISFIFO (170), S ISSOCK (171) See also: ISLNK. S ISCHR Declaration: Function S ISCHR (m:integer) : boolean; Description: S ISCHR checks the file mode m to see whether the file is a character device file. If so it returns True. Errors: FStat (159), S ISLNK (170), S ISREG (171), S ISDIR (170), S ISBLK (169), S ISFIFO (170), S ISSOCK (171) See also: ISLNK. 169 8.2. FUNCTIONS AND PROCEDURES S ISDIR Declaration: Function S ISDIR (m:integer) : boolean; Description: S ISDIR checks the file mode m to see whether the file is a directory. If so it returns True Errors: FStat (159), S ISLNK (170), S ISREG (171), S ISCHR (169), S ISBLK (169), S ISFIFO (170), S ISSOCK (171) See also: ISLNK. S ISFIFO Declaration: Function S ISFIFO (m:integer) : boolean; Description: S ISFIFO checks the file mode m to see whether the file is a fifo (a named pipe). If so it returns True. Errors: FStat (159), S ISLNK (170), S ISREG (171), S ISDIR (170), S ISCHR (169), S ISBLK (169), S ISSOCK (171) See also: ISLNK. S ISLNK Declaration: Function S ISLNK (m:integer) : boolean; Description: S ISLNK checks the file mode m to see whether the file is a symbolic link. If so it returns True Errors: FStat (159), S ISREG (171), S ISDIR (170), S ISCHR (169), S ISBLK (169), S ISFIFO (170), S ISSOCK (171) Program Example53 ; { Program to demonstrate the S ISLNK f u n c t i o n . } Uses l i n u x ; Var I n f o : Stat ; begin i f FStat ( paramstr ( 1 ) , i n f o ) then begin i f S ISLNK( i n f o . mode ) then Writeln ( ' F i l e i s a l i n k ' ) ; i f S ISREG( i n f o . mode ) then Writeln ( ' F i l e i s a r e g u l a r f i l e ' ) ; i f S ISDIR ( i n f o . mode ) then Writeln ( ' F i l e i s a d i r e c t o r y ' ) ; i f S ISCHR( i n f o . mode ) then Writeln ( ' F i l e i s a c h a r a c t e r d e v i c e f i l e ' ) ; i f S ISBLK( i n f o . mode ) then Writeln ( ' F i l e i s a block d e v i c e f i l e ' ) ; i f S ISFIFO ( i n f o . mode ) then Writeln ( ' F i l e i s a named pipe ( FIFO ) ' ) ; 170 8.2. FUNCTIONS AND PROCEDURES i f S ISSOCK( i n f o . mode ) then Writeln ( ' F i l e i s a socket ' ) ; end ; end . See also: S ISREG Declaration: Function S ISREG (m:integer) : boolean; Description: S ISREG checks the file mode m to see whether the file is a regular file. If so it returns True Errors: FStat (159), S ISLNK (170), S ISDIR (170), S ISCHR (169), S ISBLK (169), S ISFIFO (170), S ISSOCK (171) See also: ISLNK. S ISSOCK Declaration: Function S ISSOCK (m:integer) : boolean; Description: S ISSOCK checks the file mode m to see whether the file is a socket. If so it returns True. Errors: FStat (159), S ISLNK (170), S ISREG (171), S ISDIR (170), S ISCHR (169), S ISBLK (169), S ISFIFO (170) See also: ISLNK. Kill Declaration: Function Kill Pid : Longint; Sig : Integer) : Integer; Description: Send a signal Sig to a process or process group. If Pid¿0 then the signal is sent to Pid, if it equals -1, then the signal is sent to all processes except process 1. If Pid¡-1 then the signal is sent to process group -Pid. The return value is zero, except in case three, where the return value is the number of processes to which the signal was sent. Errors: LinuxError is used to report errors: sys einvalAn invalid signal is sent. sys esrchThe Pid or process group don't exist. sys epermThe e ective userid of the current process doesn't math the one of process Pid. See also: SigAction (181), Signal (183), Kill (2) 171 8.2. FUNCTIONS AND PROCEDURES LStat Declaration: Function LStat (Path : Pathstr; Var Info : stat) : Boolean; Description: LStat gets information about the link specified in Path, and stores it in Info, which is of type stat. Contrary to FStat, it stores information about the link, not about the file the link points to. The function returns True if the call was succesfull, False if the call failed. Errors: LinuxError is used to report errors. sys enoentPath does not exist. See also: FStat (159), FSStat (158), stat (2) program example29 ; { Program to demonstrate the LStat f u n c t i o n . } uses l i n u x ; var f : text ; i : byte ; i n f o : s t a t ; begin { Make a f i l e } a s s i g n ( f , ' t e s t . f i l ' ) ; rewrite ( f ) ; for i :=1 to 10 do writeln ( f , ' T e s t l i n e # ' , i ) ; c l o s e ( f ) ; { Do the c a l l on made f i l e . } i f not f s t a t ( ' t e s t . f i l ' , i n f o ) then begin writeln ( ' Fstat f a i l e d . Errno : ' , l i n u x e r r o r ) ; halt ( 1 ) ; end ; writeln ; writeln ( ' Result of f s t a t on f i l e ' ' t e s t . f i l ' ' . ' ) ; writeln ( ' Inode : ' , i n f o . ino ) ; writeln ( ' Mode : ' , i n f o . mode ) ; writeln ( ' n l i n k : ' , i n f o . n l i n k ) ; writeln ( ' uid : ' , i n f o . uid ) ; writeln ( ' gid : ' , i n f o . gid ) ; writeln ( ' rdev : ' , i n f o . rdev ) ; writeln ( ' Size : ' , i n f o . s i z e ) ; writeln ( ' B l k s i z e : ' , i n f o . b l k s z e ) ; writeln ( ' Blocks : ' , i n f o . blocks ) ; writeln ( ' atime : ' , i n f o . atime ) ; writeln ( ' mtime : ' , i n f o . mtime ) ; writeln ( ' ctime : ' , i n f o . ctime ) ; I f not SymLink ( ' t e s t . f i l ' , ' t e s t . lnk ' ) then writeln ( ' Link f a i l e d ! Errno : ' , l i n u x e r r o r ) ; i f not l s t a t ( ' t e s t . lnk ' , i n f o ) then 172 8.2. FUNCTIONS AND PROCEDURES begin writeln ( ' LStat f a i l e d . Errno : ' , l i n u x e r r o r ) ; halt ( 1 ) ; end ; writeln ; writeln ( ' Result of f s t a t on f i l e ' ' t e s t . lnk ' ' . ' ) ; writeln ( ' Inode : ' , i n f o . ino ) ; writeln ( ' Mode : ' , i n f o . mode ) ; writeln ( ' n l i n k : ' , i n f o . n l i n k ) ; writeln ( ' uid : ' , i n f o . uid ) ; writeln ( ' gid : ' , i n f o . gid ) ; writeln ( ' rdev : ' , i n f o . rdev ) ; writeln ( ' Size : ' , i n f o . s i z e ) ; writeln ( ' B l k s i z e : ' , i n f o . b l k s z e ) ; writeln ( ' Blocks : ' , i n f o . blocks ) ; writeln ( ' atime : ' , i n f o . atime ) ; writeln ( ' mtime : ' , i n f o . mtime ) ; writeln ( ' ctime : ' , i n f o . ctime ) ; { Remove f i l e and l i n k } erase ( f ) ; u n l i n k ( ' t e s t . lnk ' ) ; end . Link Declaration: Function Link (OldPath,NewPath : pathstr) : Boolean; Description: Link makes NewPath point to the same file als OldPath. The two files then have the same inode number. This is known as a 'hard' link. The function returns True if the call was succesfull, False if the call failed. Errors: Errors are returned in LinuxError. sys exdevOldPath and NewPath are not on the same filesystem. sys epermThe filesystem containing oldpath and newpath doesn't support linking files. sys eaccessWrite access for the directory containing Newpath is disallowed, or one of the directories in OldPath or NewPath has no search (=execute) permission. sys enoentA directory entry in OldPath or NewPath does not exist or is a symbolic link pointing to a non-existent directory. sys enotdirA directory entry in OldPath or NewPath is nor a directory. sys enomemInsu cient kernel memory. sys erofsThe files are on a read-only filesystem. sys eexistNewPath already exists. sys emlinkOldPath has reached maximal link count. sys eloopOldPath or NewPath has a reference to a circular symbolic link, i.e. a symbolic link, whose expansion points to itself. sys enospcThe device containing NewPath has no room for anothe entry. sys epermOldPath points to . or .. of a directory. See also: SymLink (184), UnLink (188), Link (2) 173 8.2. FUNCTIONS AND PROCEDURES Program Example21 ; { Program to demonstrate the Link and UnLink f u n c t i o n s . } Uses l i n u x ; Var F : Text ; S : String ; begin Assign ( F, ' t e s t . txt ' ) ; Rewrite ( F ) ; Writeln ( F, ' This i s w r i t t e n to t e s t . txt ' ) ; Close ( f ) ; { new . txt and t e s t . txt are now the same f i l e } i f not Link ( ' t e s t . txt ' , ' new . txt ' ) then writeln ( ' Error when l i n k i n g ! ' ) ; { Removing t e s t . txt s t i l l l e a v e s new . txt } I f not Unlink ( ' t e s t . txt ' ) then Writeln ( ' Error when u n l i n k i n g ! ' ) ; Assign ( f , ' new . txt ' ) ; Reset ( F ) ; While not EOF( f ) do begin Readln ( F, S ) ; Writeln ( '> ' , s ) ; end ; Close ( f ) ; { Remove new . txt a l s o } I f not Unlink ( ' new . txt ' ) then Writeln ( ' Error when u n l i n k i n g ! ' ) ; end . LocalToEpoch Declaration: Function LocalToEpoch (Year,Month,Day,Hour,Minute,Second : Word) : longint; Description: Converts the Local time to epoch time (=Number of seconds since 00:00:00 , January 1, 1970 ). Errors: None See also: GetEpochTime (163), EpochToLocal (148), GetTime (166),GetDate (161) Program Example4 ; { Program to demonstrate the LocalToEpoch f u n c t i o n . } Uses l i n u x ; Var year , month , day , hour , minute , second : Word ; begin Write ( ' Year : ' ) ; readln ( Year ) ; Write ( ' Month : ' ) ; readln ( Month ) ; 174 8.2. FUNCTIONS AND PROCEDURES Write ( ' Day : ' ) ; readln ( Day ) ; Write ( ' Hour : ' ) ; readln ( Hour ) ; Write ( ' Minute : ' ) ; readln ( Minute ) ; Write ( ' Seonds : ' ) ; readln ( Second ) ; Write ( ' This i s : ' ) ; Write ( LocalToEpoch ( year , month , day , hour , minute , second ) ) ; Writeln ( ' seconds past 00:00 1/1/1980' ) ; end . MkFifo Declaration: Function MkFifo (PathName: String; Mode : Longint) : Boolean; Description: MkFifo creates named a named pipe in the filesystem, with name PathName and mode Mode. Errors: LinuxError is used to report errors: sys emfileToo many file descriptors for this process. sys enfileThe system file table is full. See also: POpen (177), MkFifo (175), mkfifo (4) Nice Declaration: Procedure Nice ( N : Integer); Description: Nice adds -N to the priority of the running process. The lower the priority numer- ically, the less the process is favored. Only the superuser can specify a negative N, i.e. increase the rate at which the process is run. Errors: Errors are returned in LinuxError sys epermA non-superuser tried to specify a negative N, i.e. do a priority increase. See also: GetPriority (166), SetPriority (180), Nice (2) Program Example15 ; { Program to demonstrate the Nice and Get / S e t P r i o r i t y f u n c t i o n s . } Uses l i n u x ; begin writeln ( ' S e t t i n g p r i o r i t y to 5' ) ; s e t p r i o r i t y ( p r i o p r o c e s s , getpid , 5 ) ; writeln ( ' New p r i o r i t y = ' , g e t p r i o r i t y ( p r i o p r o c e s s , getpid ) ) ; writeln ( ' Doing nice 10' ) ; nice ( 1 0 ) ; writeln ( ' New P r i o r i t y = ' , g e t p r i o r i t y ( p r i o p r o c e s s , getpid ) ) ; end . 175 8.2. FUNCTIONS AND PROCEDURES OpenDir Declaration: Function OpenDir (f:pchar) : pdir; Description: OpenDir opens the directory f, and returns a pdir pointer to a Dir record, which can be used to read the directory structure. If the directory cannot be opened, nil is returned. Errors: Errors are returned in LinuxError. See also: CloseDir (146), ReadDir (178), SeekDir (178), TellDir (188), opendir (3) Program Example35 ; { Program to demonstrate the OpenDir , ReadDir , SeekDir and T e l l D i r f u n c t i o n s . } Uses l i n u x ; Var TheDir : PDir ; ADirent : PDirent ; Entry : Longint ; begin TheDir := OpenDir ( ' . / . ' ) ; Repeat Entry := T e l l D i r ( TheDir ) ; ADirent := ReadDir ( TheDir ) ; I f ADirent<>Nil then With ADirent do begin Writeln ( ' Entry No : ' , Entry ) ; Writeln ( ' Inode : ' , ino ) ; Writeln ( ' O f f s e t : ' , o f f ) ; Writeln ( ' Reclen : ' , r e c l e n ) ; Writeln ( ' Name : ' , pchar ( @name [ 0 ] ) ) ; end ; Until ADirent =Nil ; Repeat Write ( ' Entry No. you would l i k e to see again (-1 to stop ) : ' ) ; ReadLn ( Entry ) ; I f Entry <>-1 then begin SeekDir ( TheDir , Entry ) ; ADirent := ReadDir ( TheDir ) ; I f ADirent<>Nil then With ADirent do begin Writeln ( ' Entry No : ' , Entry ) ; Writeln ( ' Inode : ' , ino ) ; Writeln ( ' O f f s e t : ' , o f f ) ; Writeln ( ' Reclen : ' , r e c l e n ) ; Writeln ( ' Name : ' , pchar ( @name [ 0 ] ) ) ; end ; end ; 176 8.2. FUNCTIONS AND PROCEDURES Until Entry =-1; Cl oseDir ( TheDir ) ; end . PClose Declaration: Function PClose (Var F : FileType) : longint; Description: PClose closes a file opened with POpen. It waits for the command to complete, and then returns the exit status of the command. Errors: LinuxError is used to report errors. If it is di erent from zero, the exit status is not valid. See also: POpen (177) For an example, see POpen (177) POpen Declaration: Procedure POpen (Var F : FileType; Cmd : pathstr; rw : char); Description: Popen runs the command specified in Cmd, and redirects the standard in or output of the command to the other end of the pipe F. The parameter rw indicates the direction of the pipe. If it is set to 'W', then F can be used to write data, which will then be read by the command from stdinput. If it is set to 'R', then the standard output of the command can be read from F. F should be reset or rewritten prior to using it. F can be of type Text or File. A file opened with POpen can be closed with Close, but also with PClose (177). The result is the same, but PClose returns the exit status of the command Cmd. Errors: Errors are reported in LinuxError and are essentially those of the Execve, Dup and AssignPipe commands. See also: AssignPipe (140), popen (3) , PClose (177) Program Example37 ; { Program to demonstrate the Popen f u n c t i o n . } uses l i n u x ; var f : text ; i : l o n g i n t ; begin writeln ( ' Creating a s h e l l s c r i p t to which echoes i t s arguments ' ) ; writeln ( ' and input back to stdout ' ) ; a s s i g n ( f , ' t es t 21 a ' ) ; rewrite ( f ) ; writeln ( f , '#!/ bin / sh ' ) ; writeln ( f , ' echo t h i s i s the c h i l d speaking . . . . ' ) ; writeln ( f , ' echo got arguments \ " $ "\ ' ) ; writeln ( f , ' cat ' ) ; 177 8.2. FUNCTIONS AND PROCEDURES writeln ( f , ' e x i t 2' ) ; writeln ( f ) ; c l o s e ( f ) ; chmod ( ' tes t2 1 a ' , o c t a l ( 7 5 5 ) ) ; popen ( f , ' . / t es t2 1 a arg1 arg2 ' , 'W' ) ; i f l i n u x e r r o r <>0 then writeln ( ' e r r o r from POpen : L i n u x e r r o r : ' , L i n u x e r r o r ) ; for i :=1 to 10 do writeln ( f , ' This i s w r i t t e n to the pipe , and should appear on stdout . ' ) ; Flush ( f ) ; Writeln ( ' The s c r i p t e x i t e d with s t a t u s : ' , PClose ( f ) ) ; writeln ; writeln ( ' Press to remove s h e l l s c r i p t . ' ) ; readln ; a s s i g n ( f , ' t es t 2 1 a ' ) ; erase ( f ) end . ReadDir Declaration: Function ReadDir (p:pdir) : pdirent; Description: ReadDir reads the next entry in the directory pointed to by p. It returns a pdirent pointer to a structure describing the entry. If the next entry can't be read, Nil is returned. Errors: Errors are returned in LinuxError. See also: CloseDir (146), OpenDir (176), SeekDir (178), TellDir (188), readdir (3) For an example, see OpenDir (176). SeekDir Declaration: Procedure SeekDir (p:pdir;off:longint); Description: SeekDir sets the directory pointer to the off-th entry in the directory structure pointed to by p. Errors: Errors are returned in LinuxError. See also: CloseDir (146), ReadDir (178), OpenDir (176), TellDir (188), seekdir (3) For an example, see OpenDir (176). Select Declaration: Function Select (N : Longint; var readfds,writefds,exceptfds : PFDset; Var Timeout) : Longint; Description: Select checks one of the file descriptors in the FDSets to see if its status changed. readfds, writefds and exceptfds are pointers to arrays of 256 bits. If you want a file descriptor to be checked, you set the corresponding element in the array to 1. The other elements in the array must be set to zero. Three arrays are passed : The 178 8.2. FUNCTIONS AND PROCEDURES entries in readfds are checked to see if characters become available for reading. The entries in writefds are checked to see if it is OK to write to them, while entries in exceptfds are cheked to see if an exception occorred on them. You can use the functions FD ZERO (153), FD Clr (153), FD Set (154), FD IsSet (153) to manipulate the individual elements of a set. The pointers can be nil. N is the largest index of a nonzero entry plus 1. (= the largest file-descriptor + 1). TimeOut can be used to set a time limit. If TimeOut can be two types : 1.TimeOut is of type PTime and contains a zero time, the call returns immediately. If TimeOut is Nil, the kernel will wait forever, or until a status changed. 2.TimeOut is of type Longint. If it is -1, this has the same e ect as a Timeout of type PTime which is Nil. Otherwise, TimeOut contains a time in milliseconds. When the TimeOut is reached, or one of the file descriptors has changed, the Select call returns. On return, it will have modified the entries in the array which have actually changed, and it returns the number of entries that have been changed. If the timout was reached, and no decsriptor changed, zero is returned; The arrays of indexes are undefined after that. On error, -1 is returned. Errors: On error, the function returns -1, and Errors are reported in LinuxError : SYS EBADF An invalid descriptot was specified in one of the sets. SYS EINTR A non blocked signal was caught. SYS EINVAL N is negative or too big. SYS ENOMEM Select was unable to allocate memory for its internal tables. See also: SelectText (180), GetFS (164), FD ZERO (153), FD Clr (153), FD Set (154), FD IsSet (153) Program Example33 ; { Program to demonstrate the S e l e c t f u n c t i o n . } Uses l i n u x ; Var FDS : FDSet ; begin FD Zero ( FDS) ; FD Set ( 0 , FDS) ; Writeln ( ' Press the to continue the program . ' ) ; { Wait u n t i l F i l e d e s c r i p t o r 0 (= Input ) changes } S e l e c t ( 1 , @FDS, n i l , n i l , n i l ) ; { Get r i d of in b u f f e r } readln ; Writeln ( ' Press key in l e s s than 2 seconds . . . ' ) ; FD Zero ( FDS) ; FD Set ( 0 , FDS) ; i f S e l e c t ( 1 , @FDS, n i l , n i l ,2000)>0 then Writeln ( ' Thank you ! ' ) { FD ISSET (0, FDS) would be true here . } else Writeln ( ' Too l a t e ! ' ) ; end . 179 8.2. FUNCTIONS AND PROCEDURES SelectText Declaration: Function SelectText ( var T : Text; TimeOut :PTime) : Longint; Description: SelectText executes the Select (178) call on a file of type Text. You can specify a timeout in TimeOut. The SelectText call determines itself whether it should check for read or write, depending on how the file was opened : With Reset it is checked for reading, with Rewrite and Append it is checked for writing. Errors: See Select (178). SYS EBADF can also mean that the file wasn't opened. See also: Select (178), GetFS (164) SetPriority Declaration: Function SetPriority (Which,Who,Prio : Integer) : Integer; Description: SetPriority sets the priority with which a process is running. Which process(es) is determined by the Which and Who variables. Which can be one of the pre-defined Prio Process, Prio PGrp, Prio User, in which case Who is the process ID, Process group ID or User ID, respectively. Prio is a value in the range -20 to 20. Errors: Error checking must be done on LinuxError, since a priority can be negative. sys esrchNo process found using which and who. sys einvalWhich was not one of Prio Process, Prio Grp or Prio User. sys epermA process was found, but neither its e ective or real user ID match the e ective user ID of the caller. sys eaccesA non-superuser tried to a priority increase. See also: GetPriority (166), Nice (175), Setpriority (2) For an example, see Nice (175). Shell Declaration: Function Shell (Command : String) : Longint; Description: Shell invokes the bash shell (/bin/sh), and feeds it the command Command (using the -c option). The function then waits for the command to complete, and then returns the exit status of the command, or 127 if it could not complete the Fork (161) or Execve (151) calls. Errors: Errors are reported in LinuxError. See also: POpen (177), Fork (161), Execve (151), system (3) program example56 ; uses l i n u x ; { Program to demonstrate the S h e l l f u n c t i o n } Var S : Longint ; begin 180 8.2. FUNCTIONS AND PROCEDURES Writeln ( ' Output of l s -l . pp ' ) ; S:= S h e l l ( ' l s -l . pp ' ) ; Writeln ( ' Command e x i t e d wwith s t a t u s : ' , S ) ; end . SigAction Declaration: Procedure SigAction (Signum : Integer; Var Act,OldAct : PSigActionRec); Description: Changes the action to take upon receipt of a signal. Act and Oldact are pointers to a SigActionRec record. SigNum specifies the signal, and can be any signal except SIGKILL or SIGSTOP. If Act is non-nil, then the new action for signal SigNum is taken from it. If OldAct is non-nil, the old action is stored there. Sa Handler may be SIG DFL for the default action or SIG IGN to ignore the signal. Sa Mask Specifies which signals should be ignord during the execution of the signal handler. Sa Flags Speciefies a series of flags which modify the behaviour of the signal handler. You can 'or' none or more of the following : SA NOCLDSTOPIf signum is SIGCHLD do not receive notification when child processes stop. SA ONESHOT or SA RESETHANDRestore the signal action to the default state once the signal handler has been called. SA RESTARTFor compatibility with BSD signals. SA NOMASK or SA NODEFERDo not prevent the signal from being re- ceived from within its own signal handler. Errors: LinuxError is used to report errors. sys einvalan invalid signal was specified, or it was SIGKILL or SIGSTOP. sys efaultAct,OldAct point outside this process address space sys eintrSystem call was interrupted. See also: SigProcMask (182), SigPending (182), SigSuspend (183), Kill (171), Sigaction (2) Program example57 ; { Program to demonstrate the SigAction f u n c t i o n .} {do a kill -USR1 pid from another terminal to see what happens . r e p l a c e pid with the r e a l pid of t h i s program . You can get t h i s pid by running ' ps ' . } uses Linux ; Varoa, na : PSigActionRec ; Procedure DoSig ( s i g : Longint ) ; cdecl ; begin writeln ( ' R e c e i v i n g s i g n a l : ' , s i g ) ; 181 8.2. FUNCTIONS AND PROCEDURES end ; begin new( na ) ; new( oa ) ; na . Sa Handler :=@DoSig ; na . Sa Mask :=0; na . Sa Flags :=0; na . Sa Restorer := Nil ; SigAction ( SigUsr1 , na , oa ) ; i f L i n u x E r r o r <>0 then begin writeln ( ' Error : ' , l i n u x e r r o r , ' . ' ) ; halt ( 1 ) ; end ; Writeln ( ' Send USR1 s i g n a l or p r e s s to e x i t ' ) ; readln ; end . SigPending Declaration: Function SigPending : SigSet; Description: Sigpending allows the examination of pending signals (which have been raised while blocked.) The signal mask of pending signals is returned. Errors: None See also: SigAction (181), SigProcMask (182), SigSuspend (183), Signal (183), Kill (171), Sigpending (2) SigProcMask Declaration: Procedure SigProcMask (How : Integer; SSet,OldSSet : PSigSet); Description: Changes the list of currently blocked signals. The behaviour of the call depends on How : SIG BLOCKThe set of blocked signals is the union of the current set and the SSet argument. SIG UNBLOCKThe signals in SSet are removed from the set of currently blocked signals. SIG SETMASKThe list of blocked signals is set so SSet. If OldSSet is non-nil, then the old set is stored in it. Errors: LinuxError is used to report errors. sys efaultSSet or OldSSet point to an adress outside the range of the process. sys eintrSystem call was interrupted. See also: SigAction (181), SigPending (182), SigSuspend (183), Kill (171), Sigprocmask (2) 182 8.2. FUNCTIONS AND PROCEDURES SigSuspend Declaration: Procedure SigSuspend (Mask : SigSet); Description: SigSuspend temporarily replaces the signal mask for the process with the one given in Mask, and then suspends the process until a signal is received. Errors: None See also: SigAction (181), SigProcMask (182), SigPending (182), Signal (183), Kill (171), SigSuspend (2) Signal Declaration: Function Signal (SigNum : Integer; Handler : SignalHandler) : SignalHandler; Description: Signal installs a new signal handler for signal SigNum. This call has the same functionality as the SigAction call. The return value for Signal is the old signal handler, or nil on error. Errors: LinuxError is used to report errors : SIG ERRAn error occurred. See also: SigAction (181),Kill (171), Signal (2) Program example58 ; { Program to demonstrate the S i g n a l f u n c t i o n .} {do a kill -USR1 pid from another terminal to see what happens . r e p l a c e pid with the r e a l pid of t h i s program . You can get t h i s pid by running ' ps ' . } uses Linux ; Procedure DoSig ( s i g : Longint ) ; cdecl ; begin writeln ( ' R e c e i v i n g s i g n a l : ' , s i g ) ; end ; begin SigNal ( SigUsr1 , @DoSig ) ; i f L i n u x E r r o r <>0 then begin writeln ( ' Error : ' , l i n u x e r r o r , ' . ' ) ; halt ( 1 ) ; end ; Writeln ( ' Send USR1 s i g n a l or p r e s s to e x i t ' ) ; readln ; end . 183 8.2. FUNCTIONS AND PROCEDURES SymLink Declaration: Function SymLink (OldPath,NewPath : pathstr) : Boolean; Description: SymLink makes Newpath point to the file in OldPath, which doesn't necessarily exist. The two files DO NOT have the same inode number. This is known as a 'soft' link. The permissions of the link are irrelevant, as they are not used when following the link. Ownership of the file is only checked in case of removal or renaming of the link. The function returns True if the call was succesfull, False if the call failed. Errors: Errors are returned in LinuxError. sys epermThe filesystem containing oldpath and newpath doesn't support linking files. sys eaccessWrite access for the directory containing Newpath is disallowed, or one of the directories in OldPath or NewPath has no search (=execute) permission. sys enoentA directory entry in OldPath or NewPath does not exist or is a symbolic link pointing to a non-existent directory. sys enotdirA directory entry in OldPath or NewPath is nor a directory. sys enomemInsu cient kernel memory. sys erofsThe files are on a read-only filesystem. sys eexistNewPath already exists. sys eloopOldPath or NewPath has a reference to a circular symbolic link, i.e. a symbolic link, whose expansion points to itself. sys enospcThe device containing NewPath has no room for anothe entry. See also: Link (173), UnLink (188), Symlink (2) Program Example22 ; { Program to demonstrate the SymLink and UnLink f u n c t i o n s . } Uses l i n u x ; Var F : Text ; S : String ; begin Assign ( F, ' t e s t . txt ' ) ; Rewrite ( F ) ; Writeln ( F, ' This i s w r i t t e n to t e s t . txt ' ) ; Close ( f ) ; { new . txt and t e s t . txt are now the same f i l e } i f not SymLink ( ' t e s t . txt ' , ' new . txt ' ) then writeln ( ' Error when s y m l i n k i n g ! ' ) ; { Removing t e s t . txt s t i l l l e a v e s new . txt Pointing now to a non-e x i s t e n t f i l e ! } I f not Unlink ( ' t e s t . txt ' ) then Writeln ( ' Error when u n l i n k i n g ! ' ) ; Assign ( f , ' new . txt ' ) ; { This should f a i l , s i n c e the symbolic l i n k p o i n t s to a non-e x i s t e n t f i l e ! } 184 8.2. FUNCTIONS AND PROCEDURES { $i -} Reset ( F ) ; { $i +} I f IOResult =0 then Writeln ( ' This shouldn ' ' t happen ' ) ; { Now remove new . txt a l s o } I f not Unlink ( ' new . txt ' ) then Writeln ( ' Error when u n l i n k i n g ! ' ) ; end . TCDrain Declaration: Function TCDrain (Fd:longint) : Boolean; Description: TCDrain waits until all data to file descriptor Fd is transmitted. The function returns True if the call was succesfull, False otherwise. Errors: Errors are reported in LinuxError See also: termios (2) TCFlow Declaration: Function TCFlow (Fd,Act:longint) : Boolean; Description: TCFlow suspends/resumes transmission or reception of data to or from the file descriptor Fd, depending on the action Act. This can be one of the following pre- defined values: TCOOFF suspend reception/transmission, TCOON resume reception/transmission, TCIOFF transmit a stop character to stop input from the terminal, TCION transmit start to resume input from the terminal. The function returns True if the call was succesfull, False otherwise. Errors: Errors are reported in LinuxError. See also: termios (2) TCFlush Declaration: Function TCFlush (Fd,QSel:longint) : Boolean; Description: TCFlush discards all data sent or received to/from file descriptor fd. QSel indicates which queue should be discard. It can be one of the following pre-defined values : TCIFLUSH input, TCOFLUSH output, TCIOFLUSH both input and output. The function returns True if the call was succesfull, False otherwise. Errors: Errors are reported in LinuxError. See also: termios (2) 185 8.2. FUNCTIONS AND PROCEDURES TCGetAttr Declaration: Function TCGetAttr (fd:longint;var tios:TermIOS) : Boolean; Description: TCGetAttr gets the terminal parameters from the terminal referred to by the file descriptor fd and returns them in a TermIOS structure tios. The function returns True if the call was succesfull, False otherwise. Errors: Errors are reported in LinuxError See also: TCSetAttr (187), termios (2) Program Example55 ; uses Linux ; { Program to demonstrate the TCGetAttr / TCSetAttr /CFMakeRaw f u n c t i o n s . } procedure ShowTermios ( var t i o s : Termios ) ; begin WriteLn ( ' Input Flags : $ ' , h e x s t r ( t i o s . c i f l a g ,8)+#13); WriteLn ( ' Output Flags : $ ' , h e x s t r ( t i o s . c oflag , 8 ) ) ; WriteLn ( ' Line Flags : $ ' , h e x s t r ( t i o s . c l f l a g , 8 ) ) ; WriteLn ( ' Control Flags : $ ' , h e x s t r ( t i o s . c cflag , 8 ) ) ; end ; varoldios , t i o s : Termios ; begin WriteLn ( ' Old a t t r i b u t e s : ' ) ; TCGetAttr (1, t i o s ) ; ShowTermios ( t i o s ) ; o l d i o s := t i o s ; Writeln ( ' S e t t i n g raw t e r m i n a l mode ' ) ; CFMakeRaw( t i o s ) ; TCSetAttr (1, TCSANOW, t i o s ) ; WriteLn ( ' Current a t t r i b u t e s : ' ) ; TCGetAttr (1, t i o s ) ; ShowTermios ( t i o s ) ; TCSetAttr (1, TCSANOW, o l d i o s ) ; end . TCGetPGrp Declaration: Function TCGetPGrp (Fd:longint;var Id:longint) : boolean; Description: TCGetPGrp returns the process group ID of a foreground process group in Id The function returns True if the call was succesfull, False otherwise Errors: Errors are reported in LinuxError See also: termios (2) 186 8.2. FUNCTIONS AND PROCEDURES TCSendBreak Declaration: Function TCSendBreak (Fd,Duration:longint) : Boolean; Description: TCSendBreak Sends zero-valued bits on an asynchrone serial connection decsribed by file-descriptor Fd, for duration Duration. The function returns True if the action was performed successfully, False otherwise. Errors: Errors are reported in LinuxError. See also: termios (2) TCSetAttr Declaration: Function TCSetAttr (Fd:longint;OptAct:longint;var Tios:TermIOS) : Boolean; Description: TCSetAttr Sets the terminal parameters you specify in a TermIOS structure Tios for the terminal referred to by the file descriptor Fd. OptAct specifies an optional action when the set need to be done, this could be one of the following pre-defined values: TCSANOW set immediately. TCSADRAIN wait for output. TCSAFLUSH wait for output and discard all input not yet read. The function Returns True if the call was succesfull, False otherwise. Errors: Errors are reported in LinuxError. See also: TCGetAttr (186), termios (2) For an example, see TCGetAttr (186). TCSetPGrp Declaration: Function TCSetPGrp (Fd,Id:longint) : boolean; Description: TCSetPGrp Sets the Process Group Id to Id. The function returns True if the call was successful, False otherwise. Errors: Errors are returned in LinuxError. See also: TCGetPGrp (186), termios (2) For an example, see TCGetPGrp (186). TTYName Declaration: Function TTYName (var f) : String; Description: Returns the name of the terminal pointed to by f. f must be a terminal. f can be of type: 1.longint for file handles; 2.Text for text variables such as input etc. Errors: Returns an empty string in case of an error. Linuxerror may be set to indicate what error occurred, but this is uncertain. See also: IsATTY (169),IOCtl (168) 187 8.2. FUNCTIONS AND PROCEDURES TellDir Declaration: Function TellDir (p:pdir) : longint; Description: TellDir returns the current location in the directory structure pointed to by p. It returns -1 on failure. Errors: Errors are returned in LinuxError. See also: CloseDir (146), ReadDir (178), SeekDir (178), OpenDir (176), telldir (3) For an example, see OpenDir (176). Umask Declaration: Function Umask (Mask : Integer) : Integer; Description: Change the file creation mask for the current user to Mask. The current mask is returned. Errors: None See also: Chmod (144), Umask (2) Program Example27 ; { Program to demonstrate the Umask f u n c t i o n . } Uses l i n u x ; begin Writeln ( ' Old Umask was : ' , Umask( Octal ( 1 1 1 ) ) ) ; WRiteln ( ' New Umask i s : ' , Octal ( 1 1 1 ) ) ; end . Uname Declaration: Procedure Uname (var unamerec:utsname); Description: Uname gets the name and configuration of the current linux kernel, and returns it in unamerec. Errors: LinuxError is used to report errors. See also: GetHostName (165), GetDomainName (162), uname (2) UnLink Declaration: Function UnLink (Var Path) : Boolean; Description: UnLink decreases the link count on file Path. Path can be of type PathStr or PChar. If the link count is zero, the file is removed from the disk. The function returns True if the call was succesfull, False if the call failed. Errors: Errors are returned in LinuxError. 188 8.2. FUNCTIONS AND PROCEDURES sys eaccessYou have no write access right in the directory containing Path, or you have no search permission in one of the directory components of Path. sys epermThe directory containing pathname has the sticky-bit set and the pro- cess's e ective uid is neither the uid of the file to be deleted nor that of the directory containing it. sys enoentA component of the path doesn't exist. sys enotdirA directory component of the path is not a directory. sys eisdirPath refers to a directory. sys enomemInsu cient kernel memory. sys erofsPath is on a read-only filesystem. See also: Link (173), SymLink (184), Unlink (2) For an example, see Link (173). Utime Declaration: Function Utime (path : pathstr; utim : utimbuf) : Boolean; Description: Utime sets the access and modification times of a file. the utimbuf record con- tains 2 fields, actime, and modtime, both of type Longint. They should be filled with an epoch-like time, specifying, respectively, the last access time, and the last modification time. For some filesystem (most notably, FAT), these times are the same. Errors: Errors are returned in LinuxError. sys eaccessOne of the directories in Path has no search (=execute) permission. sys enoentA directory entry in Path does not exist or is a symbolic link pointing to a non-existent directory. Other errors may occur, but aren't documented. See also: GetEpochTime (163), Chown (143), Access (139), utime (() 2) Program Example25 ; { Program to demonstrate the UTime f u n c t i o n . } Uses l i n u x ; Var utim : utimbuf ; year , month , day , hour , minute , second : Word ; begin { Set access and m o d i f i c a t i o n time of e x e c u t a b l e source } GetTime ( hour , minute , second ) ; GetDate ( year , month , day ) ; utim . actime := LocalToEpoch ( year , month , day , hour , minute , second ) ; utim . modtime := utim . actime ; i f not Utime ( ' ex25 . pp ' , utim ) then writeln ( ' C a l l to UTime f a i l e d ! ' ) else 189 8.2. FUNCTIONS AND PROCEDURES begin Write ( ' Set access and m o d i f i c a t i o n times to : ' ) ; Write ( Hour : 2 , ' : ' , minute : 2 , ' : ' , second , ' , ' ) ; Writeln ( Day : 2 , ' / ' , month : 2 , ' / ' , year : 4 ) ; end ; end . WaitPid Declaration: Function WaitPid (Pid : longint; Status : pointer; Options : Integer) : Longint; Description: WaitPid waits for a child process with process ID Pid to exit. The value of Pid can be one of the following: Pid ¡ -1Causes WaitPid to wait for any child process whose process group ID equals the absolute value of pid. Pid = -1Causes WaitPid to wait for any child process. Pid = 0Causes WaitPid to wait for any child process whose process group ID equals the one of the calling process. Pid ¿ 0Causes WaitPid to wait for the child whose process ID equals the value of Pid. The Options parameter can be used to specify further how WaitPid behaves: WNOHANGCauses Waitpid to return immediately if no child has exited. WUNTRACEDCauses WaitPid to return also for children which are stopped, but whose status has not yet been reported. Upon return, it returns the exit status of the process, or -1 in case of failure. Errors: Errors are returned in LinuxError. See also: Fork (161), Execve (151), waitpid (2) for an example, see Fork (161). 190 Chapter 9 The MMX unit This chapter describes the MMX unit. This unit allows you to use the MMX capabil- ities of the Free Pascal compiler. It was written by Florian Kl¨ampfl for the I386 processor. 9.1 Variables, Types and constants The following types are defined in the MMX unit: tmmxshortint = array[0..7] of shortint; tmmxbyte = array[0..7] of byte; tmmxword = array[0..3] of word; tmmxinteger = array[0..3] of integer; tmmxfixed = array[0..3] of fixed16; tmmxlongint = array[0..1] of longint; tmmxcardinal = array[0..1] of cardinal; { for the AMD 3D } tmmxsingle = array[0..1] of single; And the following pointers to the above types: pmmxshortint = ^tmmxshortint; pmmxbyte = ^tmmxbyte; pmmxword = ^tmmxword; pmmxinteger = ^tmmxinteger; pmmxfixed = ^tmmxfixed; pmmxlongint = ^tmmxlongint; pmmxcardinal = ^tmmxcardinal; { for the AMD 3D } pmmxsingle = ^tmmxsingle; The following initialized constants allow you to determine if the computer has MMX extensions. They are set correctly in the unit's initialization code. is_mmx_cpu : boolean = false; is_amd_3d_cpu : boolean = false; 191 9.2. FUNCTIONS AND PROCEDURES 9.2 Functions and Procedures Emms Declaration: Procedure Emms ; Description: Emms sets all floating point registers to empty. This procedure must be called after you have used any MMX instructions, if you want to use floating point arithmetic. If you just want to move floating point data around, it isn't necessary to call this function, the compiler doesn't use the FPU registers when moving data. Only when doing calculations, you should use this function. Errors: None. See also: Programmers' guide Example:: Program MMXDemo; uses mmx; vard1 : double; a : array[0..10000] of double; i : longint; begin d1:=1.0; {$mmx+} { floating point data is used, but we do _no_ arithmetic } for i:=0 to 10000 do a[i]:=d2; { this is done with 64 bit moves } {$mmx-} emms; { clear fpu } { now we can do floating point arithmetic again } end. 192 Chapter 10 The Mouse unit The mouse unit provides basic Mouse handling under Dos (Go32v1 and Go32v2) Some general remarks about the mouse unit: * The mouse driver does not know when the text screen scrolls. This results in unerased mouse cursors on the screen when the screen scrolls while the mouse cursor is visible. The solution is to hide the mouse cursor (using HideMouse) when you write something to the screen and to show it again afterwards (using ShowMouse). * All Functions/Procedures that return and/or accept coordinates of the mouse cursor, always do so in pixels and zero based (so the upper left corner of the screen is (0,0)). To get the (column, row) in standard text mode, divide both x and y by 8 (and add 1 if you want to have it 1 based). * The real resolution of graphic modes and the one the mouse driver uses can di er. For example, mode 13h (320*200 pixels) is handled by the mouse driver as 640*200, so you will have to multiply the X coordinates you give to the driver and divide the ones you get from it by 2 in that mode. * By default the mouse unit is compiled with the conditional define MouseCheck. This causes every procedure/function of the unit to check the MouseFound variable prior to doing anything. Of course this is not necessary, so if you are sure you are not calling any mouse unit procedures when no mouse is found, you can recompile the mouse unit without this conditional define. * You will notice that several procedures/functions have longint sized param- eters while only the lower 16 bits are used. This is because FPC is a 32 bit compiler and consequently 32 bit parameters result in faster code. 10.1 Constants, types and variables The following constants are defined (to be used in e.g. the GetLastButtonPress (194) call). LButton = 1; {left button} RButton = 2; {right button} MButton = 4; {middle button} The following variable exist: 193 10.2. FUNCTIONS AND PROCEDURES MouseFound: Boolean; it is set to True or False in the unit's initialization code. 10.2 Functions and procedures GetLastButtonPress Declaration: Function GetLastButtonPress (Button: Longint; Var x,y:Longint) : Longint; Description: GetLastButtonPress Stores the position where Button was last pressed in x and y and returns the number of times this button has been pressed since the last call to this function with Button as parameter. For Button you can use the LButton, RButton and MButton constants for resp. the left, right and middle button. For two-button mice, checking the status of the middle button seems to give and clear the stats of the right button. Errors: None. See also: GetLastButtonRelease (195) { example f o r GetLastButtonPress and GetLastButtonRelease } Uses Mouse , Crt ; Var x , y , times : Longint ; c : Char ; Begin I f MouseFound Then Begin ClrScr ; ShowMouse ; Writeln ( ' Move the mouse and c l i c k the buttons ( p r e s s escape to quit ) . ' ) ; Writeln ( ' Press the L-key to see the s t a t s f o r the l e f t button . ' ) ; Writeln ( ' Press the R-key to see the s t a t s f o r the r i g h t button . ' ) ; Writeln ( ' Press the M-key to see the s t a t s f o r the middle button . ' ) ; GotoXY( 1 , 1 9 ) ; Write ( ' Since the l a s t c a l l to GetLastButtonPress with t h i s button as parameter , the ' ) ; GotoXY( 1 , 2 2 ) ; Write ( ' Since the l a s t c a l l to GetLastButtonRelease with t h i s button as parameter , the ' ) ; Repeat I f Keypressed Then Begin c := UpCase( Readkey ) ; Case c Of ' L ' : Begin GotoXY ( 1 , 2 0 ) ; ClrEol ; times := GetLastButtonPress ( LButton , x , y ) ; Write ( ' l e f t button has been pr es se d ' , times , ' times , the l a s t time at ( ' , x , ' , ' , y , ' ) ' ) ; times := GetLastButtonRelease ( LButton , x , y ) ; 194 10.2. FUNCTIONS AND PROCEDURES GotoXY( 1 , 2 3 ) ; ClrEol ; Write ( ' l e f t button has been r e l e a s e d ' , times , ' times , the l a s t time at ( ' , x , ' , ' , y , ' ) ' ) End; ' R' : Begin GotoXY ( 1 , 2 0 ) ; ClrEol ; times := GetLastButtonPress ( RButton , x , y ) ; Writeln ( ' r i g h t button has been p res s ed ' , times , ' times , the l a s t time at ( ' , x , ' , ' , y , ' ) ' ) ; times := GetLastButtonRelease ( RButton , x , y ) ; GotoXY( 1 , 2 3 ) ; ClrEol ; Write ( ' r i g h t button has been r e l e a s e d ' , times , ' times , the l a s t time at ( ' , x , ' , ' , y , ' ) ' ) End; 'M' : Begin GotoXY ( 1 , 2 0 ) ; ClrEol ; times := GetLastButtonPress ( MButton , x , y ) ; Writeln ( ' middle button has been pr es se d ' , times , ' times , the l a s t time at ( ' , x , ' , ' , y , ' ) ' ) ; times := GetLastButtonRelease ( MButton , x , y ) ; GotoXY( 1 , 2 3 ) ; ClrEol ; Write ( ' middle button has been r e l e a s e d ' , times , ' times , the l a s t time at ( ' , x , ' , ' , y , ' ) ' ) End End End; Until ( c = #27); { escape } While KeyPressed do ReadKey ; GotoXY( 1 , 2 4 ) ; HideMouse End End. GetLastButtonRelease Declaration: Function GetLastButtonRelease (Button: Longint; Var x,y:Longint) : Longint; Description: GetLastButtonRelease stores the position where Button was last released in x and y and returns the number of times this button has been released since the last call to this function with Button as parameter. For button you can use the LButton, RButton and MButton constants for resp. the left, right and middle button. For two-button mice, checking the stats of the middle button seems to give and clear the stats of the right button. Errors: None. See also: GetLastButtonPress (194) 195 10.2. FUNCTIONS AND PROCEDURES For an example, see GetLastButtonPress (194). GetMouseState Declaration: Procedure GetMouseState (Var x, y, buttons: Longint); Description: GetMouseState Returns information on the current mouse position and which buttons are currently pressed. x and y return the mouse cursor coordinates in pixels. Buttons is a bitmask. Check the example program to see how you can get the necessary information from it. Errors: None. See also: LPressed (198), MPressed (198), RPressed (198), SetMousePos (200) { example f or GetMouseState , I s L P r e s s e d , IsRPressed and IsMPressed } Uses Mouse , Crt ; Var X, Y, State : Longint ; Begin I f MouseFound Then Begin ClrScr ; ShowMouse ; GotoXY( 5 , 2 4 ) ; Write ( ' Left button : ' ) ; GotoXY( 3 0 , 2 4 ) ; Write ( ' Right button : ' ) ; GotoXY( 5 5 , 2 4 ) ; Write ( ' Middle button : ' ) ; While KeyPressed do Readkey ; { c l e a r keyboard b u f f e r } Repeat GetMouseState ( x , y , State ) ; GotoXY ( 2 0 , 2 2 ) ; Write ( ' X: ' , x : 5 , ' ( column : ' , ( x div 8 ) : 2 , ' ) Y: ' , y : 5 , ' ( row : ' , ( y div 8 ) : 2 , ' ) ' ) ; GotoXY ( 1 8 , 2 4 ) ; { l e f t button } I f ( State and LButton ) = LButton Then { or : " I f LPressed Then " . I f you use t h i s f u n c t i o n , no c a l l to GetMouseState i s n e c e s s a r y } Write ( ' Down' ) Else Write ( ' Up ' ) ; GotoXY ( 4 4 , 2 4 ) ; { r i g h t button } I f ( State and RButton ) = RButton Then { or : " I f RPressed Then "} Write ( ' Down' ) Else Write ( ' Up ' ) ; GotoXY ( 7 0 , 2 4 ) ; { middle button } I f ( State and MButton ) = MButton Then { or : " I f MPressed Then "} Write ( ' Down' ) 196 10.2. FUNCTIONS AND PROCEDURES Else Write ( ' Up ' ) Until KeyPressed ; HideMouse ; While KeyPressed Do Readkey End End. HideMouse Declaration: Procedure HideMouse ; Description: HideMouse makes the mouse cursor invisible. Multiple calls to HideMouse will require just as many calls to ShowMouse to make the mouse cursor again visible. Errors: None. See also: ShowMouse (203), SetMouseHideWindow (199) For an example, see ShowMouse (203). InitMouse Declaration: Procedure InitMouse ; Description: InitMouse Initializes the mouse driver sets the variable MouseFound depending on whether or not a mouse is found. This is Automatically called at the start of your program. You should never have to call it, unless you want to reset everything to its default values. Errors: None. See also: MouseFound variable. Program Mouse1 ; { example fo r InitMouse and MouseFound } Uses Mouse ; Begin I f MouseFound Then Begin {go i n t o g r a p h i c s mode 13 h} Asmmovl $0x013, %eax pushl %ebp int $0x010 popl %ebp End; InitMouse ; ShowMouse ; { o t h e r w i s e i t s t a y s i n v i s i b l e } Writeln ( ' Mouse Found ! ( p r e s s enter to quit ) ' ) ; Readln ; 197 10.2. FUNCTIONS AND PROCEDURES { back to text mode} Asmmovl $3, %eax pushl %ebp int $0x010 popl %ebp End End End. LPressed Declaration: Function LPressed : Boolean; Description: LPressed returns True if the left mouse button is pressed. This is simply a wrapper for the GetMouseState procedure. Errors: None. See also: GetMouseState (196), MPressed (198), RPressed (198) For an example, see GetMouseState (196). MPressed Declaration: Function MPressed : Boolean; Description: MPressed returns True if the middle mouse button is pressed. This is simply a wrapper for the GetMouseState procedure. Errors: None. See also: GetMouseState (196), LPressed (198), RPressed (198) For an example, see GetMouseState (196). RPressed Declaration: Function RPressed : Boolean; Description: RPressed returns True if the right mouse button is pressed. This is simply a wrapper for the GetMouseState procedure. Errors: None. See also: GetMouseState (196), LPressed (198), MPressed (198) For an example, see GetMouseState (196). SetMouseAscii Declaration: Procedure SetMouseAscii (Ascii: Byte); 198 10.2. FUNCTIONS AND PROCEDURES Description: SetMouseAscii sets the Ascii value of the character that depicts the mouse cursor in text mode. The di erence between this one and SetMouseShape (200), is that the foreground and background colors stay the same and that the Ascii code you enter is the character that you will get on screen; there's no XOR'ing. Errors: None See also: SetMouseShape (200) { example f o r SetMouseAscii } { warning : no e r r o r checking i s performed on the input } Uses Mouse , Crt ; Var a s c i i : Byte ; x , y : Longint ; Begin I f MouseFound Then Begin ClrScr ; Writeln ( ' Press any mouse button to quit a f t e r you ' ' ve entered an A s c i i value . ' ) ; Writeln ; Writeln ( ' ASCII value of mouse c u r s o r : ' ) ; ShowMouse ; Repeat GotoXY( 3 0 , 3 ) ; ClrEol ; Readln ( a s c i i ) ; SetMouseAscii ( a s c i i ) Until ( GetLastButtonPress ( LButton , x , y ) <> 0) Or ( GetLastButtonPress ( RButton , x , y ) <> 0) Or ( GetLastButtonPress ( MButton , x , y ) <> 0); HideMouse End; End. SetMouseHideWindow Declaration: Procedure SetMouseHideWindow (xmin,ymin,xmax,ymax: Longint); Description: SetMouseHideWindow defines a rectangle on screen with top-left corner at (xmin,ymin) and botto-right corner at (xmax,ymax),which causes the mouse cursor to be turned o when it is moved into it. When the mouse is moved into the specified region, it is turned o until you call ShowMouse again. However, once you've called Show- Mouse (203), you'll have to call SetMouseHideWindow again to redefine the hide window... This may be annoying, but it's the way it's implemented in the mouse driver. While xmin, ymin, xmax and ymax are Longint parameters, only the lower 16 bits are used. Errors: None. See also: ShowMouse (203), HideMouse (197) nputlistingmouseex/mouse9.pp 199 10.2. FUNCTIONS AND PROCEDURES SetMousePos Declaration: Procedure SetMousePos (x,y:Longint); Description: SetMosusePos sets the position of the mouse cursor on the screen. x is the hor- izontal position in pixels, y the vertical position in pixels. The upper-left hand corner of the screen is the origin. While x and y are longints, only the lower 16 bits are used. Errors: None. See also: GetMouseState (196) { example f o r SetMousePos } Uses Mouse , Crt ; Begin I f MouseFound Then Begin ShowMouse ; While KeyPressed do ReadKey ; Repeat SetMousePos (Random( 8 0 8 ) , Random( 2 5 8 ) ) ; delay ( 10 0 ) ; Until Keypressed ; HideMouse ; While KeyPressed do ReadKey ; End; End. SetMouseShape Declaration: Procedure SetMouseShape (ForeColor,BackColor,Ascii: Byte); Description: SetMouseShape defines how the mouse cursor looks in textmode The character and its attributes that are on the mouse cursor's position on screen are XOR'ed with resp. ForeColor, BackColor and Ascii. Set them all to 0 for a "transparent" cursor. Errors: None. See also: SetMouseAscii (198) { example fo r SetMouseShape } { warning : no e r r o r checking i s performed on the input } { the A s c i i value you enter i s XOR' ed with the A s c i i value of the c h a r a c t e r on the screen over which you move the c u r s o r . To get a " t r a n s p a r e n t " c u r s o r , use the A s c i i value 0} Uses Mouse , Crt ; Var a s c i i , fc , bc : Byte ; x , y : Longint ; 200 10.2. FUNCTIONS AND PROCEDURES Begin I f MouseFound Then Begin ClrScr ; Writeln ( ' Press any mouse button to quit a f t e r you ' ' ve entered a sequence of numbers . ' ) ; Writeln ; Writeln ( ' ASCII value of mouse c u r s o r : ' ) ; Writeln ( ' Forground c o l o r : ' ) ; Writeln ( ' Background c o l o r : ' ) ; ShowMouse ; Repeat GotoXY( 3 0 , 3 ) ; ClrEol ; Readln ( a s c i i ) ; GotoXY( 1 8 , 4 ) ; ClrEol ; Readln ( fc ) ; GotoXY( 1 9 , 5 ) ; ClrEol ; Readln ( bc ) ; SetMouseShape ( fc , bc , a s c i i ) Until ( GetLastButtonPress ( LButton , x , y ) <> 0) Or ( GetLastButtonPress ( RButton , x , y ) <> 0) Or ( GetLastButtonPress ( MButton , x , y ) <> 0); HideMouse End; End. SetMouseSpeed Declaration: Procedure SetMouseSpeed (Horizontal, Vertical: Longint); Description: SetMouseSpeed sets the mouse speed in mickeys per 8 pixels. A mickey is the smallest measurement unit handled by a mouse. With this procedure you can set how many mickeys the mouse should move to move the cursor 8 pixels horizontally of vertically. The default values are 8 for horizontal and 16 for vertical movement. While this procedure accepts longint parameters, only the low 16 bits are actually used. Errors: None. See also: Uses Mouse , Crt ; Var hor , v e r t : Longint ; x , y : Longint ; Begin I f MouseFound Then Begin ClrScr ; Writeln ( ' C l i c k any button to quit a f t e r you ' ' ve entered a sequence of numbers . ' ) ; 201 10.2. FUNCTIONS AND PROCEDURES Writeln ; Writeln ( ' H o r i z o n t a l mickey ' ' s per p i x e l : ' ) ; Writeln ( ' V e r t i c a l mickey ' ' s per p i x e l : ' ) ; ShowMouse ; Repeat GotoXY( 3 2 , 3 ) ; ClrEol ; Readln ( hor ) ; GotoXY( 3 0 , 4 ) ; ClrEol ; Readln ( v e r t ) ; SetMouseSpeed ( hor , v e r t ) ; Until ( GetLastButtonPress ( LButton , x , y ) <> 0) Or ( GetLastButtonPress ( RButton , x , y ) <> 0) Or ( GetLastButtonPress ( MButton , x , y ) <> 0); End End. SetMouseWindow Declaration: Procedure SetMouseWindow (xmin,ymin,xmax,ymax: Longint); Description: SetMousWindow defines a rectangle on screen with top-left corner at (xmin,ymin) and botto-right corner at (xmax,ymax), out of which the mouse cursor can't move. This procedure is simply a wrapper for the SetMouseXRange (202) and SetMouseYRange (203) procedures. While xmin, ymin, xmax and ymax are Longint parameters, only the lower 16 bits are used. Errors: None. See also: SetMouseXRange (202), SetMouseYRange (203) For an example, see SetMouseXRange (202). SetMouseXRange Declaration: Procedure SetMouseXRange (Min, Max: Longint); Description: SetMouseXRange sets the minimum (Min) and maximum (Max) horizontal coordi- nates in between which the mouse cursor can move. While Min and Max are Longint parameters, only the lower 16 bits are used. Errors: None. See also: SetMouseYRange (203), SetMouseWindow (202) { example f o r SetMouseXRange , SetMouseYRange and SetMouseWindow } Uses Mouse , Crt ; Begin I f MouseFound Then Begin SetMouseXRange ( 2 0 8 , 5 0 8 ) ; { c h a r r a c t e r width and height = 8 p i x e l s } 202 10.2. FUNCTIONS AND PROCEDURES SetMouseYRange ( 1 0 8 , 1 5 8 ) ; { the two l i n e s of code have e x a c t l y the same e f f e c t as SetMouseWindow (20 8,10 8,50 8,15 8)} Writeln ( ' Press any key to quit . ' ) ; ShowMouse ; While KeyPressed Do ReadKey ; Readkey ; While KeyPressed Do ReadKey ; HideMouse End End. SetMouseYRange Declaration: Procedure SetMouseYRange (Min, Max: Longint); Description: SetMouseYRange sets the minimum (Min) and maximum (Max) vertical coordinates in between which the mouse cursor can move. While Min and Max are Longint parameters, only the lower 16 bits are used. Errors: None. See also: SetMouseXRange (202), SetMouseWindow (202) For an example, see SetMouseXRange (202). ShowMouse Declaration: Procedure ShowMouse ; Description: ShowMouse makes the mouse cursor visible. At the start of your progam, the mouse is invisible. Errors: None. See also: HideMouse (197),SetMouseHideWindow (199) { example f o r ShowMouse and HideMouse } Uses Mouse ; Begin ClrScr ; I f MouseFound Then Begin Writeln ( ' Now you can see the mouse . . . ( p r e s s enter to continue ) ' ) ; ShowMouse ; Readln ; HideMouse ; Writeln ( ' And now you can ' ' t . . . ( p r e s s enter to quit ) ' ) ; Readln End End. 203 Chapter 11 The Objects unit. This chapter documents the objects unit. The unit was implemented by many people, and was mainly taken from the FreeVision sources. The methods and fields that are in a Private part of an object declaration have been left out of this documentation. 11.1 Constants The following constants are error codes, returned by the various stream objects. CONST stOk = 0; { No stream error } stError = -1; { Access error } stInitError = -2; { Initialize error } stReadError = -3; { Stream read error } stWriteError = -4; { Stream write error } stGetError = -5; { Get object error } stPutError = -6; { Put object error } stSeekError = -7; { Seek error in stream } stOpenError = -8; { Error opening stream } These constants can be passed to constructors of file streams: CONST stCreate = $3C00; { Create new file } stOpenRead = $3D00; { Read access only } stOpenWrite = $3D01; { Write access only } stOpen = $3D02; { Read/write access } The following constants are error codes, returned by the collection list objects: CONST coIndexError = -1; { Index out of range } coOverflow = -2; { Overflow } Maximum data sizes (used in determining how many data can be used. 204 11.2. TYPES CONST MaxBytes = 128*1024*1024; { Maximum data size } MaxWords = MaxBytes DIV SizeOf(Word); { Max word data size } MaxPtrs = MaxBytes DIV SizeOf(Pointer); { Max ptr data size } MaxCollectionSize = MaxBytes DIV SizeOf(Pointer); { Max collection size } 11.2 Types The follwing auxiliary types are defined: TYPE{ Character set } TCharSet = SET Of Char; PCharSet = ^TCharSet; { Byte array } TByteArray = ARRAY [0..MaxBytes-1] Of Byte; PByteArray = ^TByteArray; { Word array } TWordArray = ARRAY [0..MaxWords-1] Of Word; PWordArray = ^TWordArray; { Pointer array } TPointerArray = Array [0..MaxPtrs-1] Of Pointer; PPointerArray = ^TPointerArray; { String pointer } PString = ^String; { Filename array } AsciiZ = Array [0..255] Of Char; Sw_Word = Cardinal; Sw_Integer = LongInt; The following records are used internaly for easy type conversion: TYPE{ Word to bytes} WordRec = packed RECORD Lo, Hi: Byte; END; { LongInt to words } LongRec = packed RECORD Lo, Hi: Word; END; { Pointer to words } PtrRec = packed RECORD Ofs, Seg: Word; END; 205 11.3. PROCEDURES AND FUNCTIONS The following record is used when streaming objects: TYPEPStreamRec = ^TStreamRec; TStreamRec = Packed RECORD ObjType: Sw_Word; VmtLink: pointer; Load : Pointer; Store: Pointer; Next : PStreamRec; END; The TPoint basic object is used in the TRect object (see section 11.4, page 209): TYPEPPoint = ^TPoint; TPoint = OBJECT X, Y: Sw_Integer; END; 11.3 Procedures and Functions NewStr Declaration: Function NewStr (Const S: String): PString; Description: NewStr makes a copy of the string S on the heap, and returns a pointer to this copy. The allocated memory is not based on the declared size of the string passed to NewStr, but is baed on the actual length of the string. Errors: If not enough memory is available, an 'out of memory' error will occur. See also: DisposeStr (207) Program ex40 ; { Program to demonstrate the NewStr f u n c t i o n } Uses Objects ; Var S : String ; P : PString ; begin S:= ' Some r e a l l y cute s t r i n g ' ; Writeln ( ' Memavail : ' , Memavail ) ; P:=NewStr( S ) ; I f P <>S then Writeln ( ' Oh-oh . . . Something i s wrong ! ! ' ) ; Writeln ( ' A l l o c a t e d s t r i n g . Memavail : ' , Memavail ) ; DisposeStr (P) ; Writeln ( ' D e a l l o c a t e d s t r i n g . Memavail : ' , Memavail ) ; end . 206 11.3. PROCEDURES AND FUNCTIONS DisposeStr Declaration: Procedure DisposeStr (P: PString); Description: DisposeStr removes a dynamically allocated string from the heap. Errors: None. See also: NewStr (206) For an example, see NewStr (206). Abstract Declaration: Procedure Abstract; Description: When implementing abstract methods, do not declare them as abstract. Instead, define them simply as virtual. In the implementation of such abstract methods, call the Abstract procedure. This allows explicit control of what happens when an abstract method is called. The current implementation of Abstract terminates the program with a run-time error 211. Errors: None. See also: Most abstract types. RegisterObjects Declaration: Procedure RegisterObjects; Description: RegisterObjects registers the following objects for streaming: 1.TCollection, see section 11.10, page 234. 2.TStringCollection, see section 11.12, page 254. 3.TStrCollection, see section 11.13, page 255. Errors: None. See also: RegisterType (207) RegisterType Declaration: Procedure RegisterType (Var S: TStreamRec); Description: RegisterType registers a new type for streaming. An object cannot be streamed unless it has been registered first. The stream record S needs to have the following fields set: ObjType: Sw WordThis should be a unique identifier. Each possible type should have it's own identifier. VmtLink: pointerThis should contain a pointer to the VMT (Virtual Method Table) of the object you try to register. You can get it with the following expression: VmtLink: Ofs(TypeOf(MyType)^); 207 11.3. PROCEDURES AND FUNCTIONS Load : Pointeris a pointer to a method that initializes an instance of that object, and reads the initial values from a stream. This method should accept as it's sole argument a PStream type variable. Store: Pointeris a pointer to a method that stores an instance of the object to a stream. This method should accept as it's sole argument a PStream type variable. Errors: In case of error (if a object with the same ObjType) is already registered), run-time error 212 occurs. Unit MyObject ; Interface Uses Objects ; Type PMyObject = TMyObject; TMyObject = Object ( TObject ) F i e l d : Longint ; Constructor I n i t ; Constructor Load ( Var Stream : TStream ) ; Destructor Done ; Procedure Store ( Var Stream : TStream ) ; Function G e t F i e l d : Longint ; Procedure S e t F i e l d ( Value : Longint ) ; end ; Implementation Constructor TMyobject . I n i t ; begin Inherited I n i t ; F i e l d :=-1; end ; Constructor TMyobject . Load ( Var Stream : TStream ) ; begin Stream . Read( F i e l d , Sizeof ( F i e l d ) ) ; end ; Destructor TMyObject . Done ; begin end ; Function TMyObject . G e t F i e l d : Longint ; begin G e t F i e l d := F i e l d ; end ; 208 11.4. TRECT Function TMyObject . S e t F i e l d ( Value : Longint ) ; begin F i e l d := Value ; end ; Procedure TMyObject . Store ( Var Stream : TStream ) ; begin Stream . Write ( F i e l d , SizeOf ( F i e l d ) ) ; end ; Const MyObjectRec : TStreamRec = ( Objtype : 6 6 6 ; vmtlink : Ofs ( TypeOf( TMyObject ) ) ; Load : @TMyObject . Load ; Store : @TMyObject . Store ; ) ; begin R e g i s t e r O b j e c t s ; RegisterType ( MyObjectRec ) ; end . LongMul Declaration: Function LongMul (X, Y: Integer): LongInt; Description: LongMul multiplies X with Y. The result is of type Longint. This avoids possible overflow errors you would normally get when multiplying X and Y that are too big. Errors: None. See also: LongDiv (209) LongDiv Declaration: Function LongDiv (X: Longint; Y: Integer): Integer; Description: LongDiv divides X by Y. The result is of type Integer instead of type Longint, as you would get normally. Errors: If Y is zero, a run-time error will be generated. See also: LongMul (209) 11.4 TRect The TRect object is declared as follows: TRect = OBJECT A, B: TPoint; 209 11.4. TRECT FUNCTION Empty: Boolean; FUNCTION Equals (R: TRect): Boolean; FUNCTION Contains (P: TPoint): Boolean; PROCEDURE Copy (R: TRect); PROCEDURE Union (R: TRect); PROCEDURE Intersect (R: TRect); PROCEDURE Move (ADX, ADY: Sw_Integer); PROCEDURE Grow (ADX, ADY: Sw_Integer); PROCEDURE Assign (XA, YA, XB, YB: Sw_Integer); END; TRect.Empty Declaration: Function TRect.Empty: Boolean; Description: Empty returns True if the rectangle defined by the corner points A, B has zero or negative surface. Errors: None. See also: TRect.Equals (211), TRect.Contains (211) Program ex1 ; { Program to demonstrate TRect . Empty } Uses o b j e c t s ; Var ARect , BRect : TRect ; P : TPoint ; begin With ARect . A do begin X:=10; Y:=10; end ; With ARect . B do begin X:=20; Y:=20; end ; { O f f s e t B by ( 5 , 5 ) } With BRect . A do begin X:=15; Y:=15; end ; With BRect . B do begin X:=25; Y:=25; end ; 210 11.4. TRECT { Point } With P do begin X:=15; Y:=15; end ; Writeln ( ' A empty : ' , ARect . Empty ) ; Writeln ( ' B empty : ' , BRect . Empty ) ; Writeln ( ' A Equals B : ' , ARect . Equals ( BRect ) ) ; Writeln ( ' A Contains ( 1 5 , 1 5 ) : ' , ARect . Contains (P) ) ; end . TRect.Equals Declaration: Function TRect.Equals (R: TRect): Boolean; Description: Equals returns True if the rectangle has the same corner points A,B as the rect- angle R, and False otherwise. Errors: None. See also: Empty (210), Contains (211) For an example, see TRect.Empty (210) TRect.Contains Declaration: Function TRect.Contains (P: TPoint): Boolean; Description: Contains returns True if the point P is contained in the rectangle (including borders), False otherwise. Errors: None. See also: Intersect (212), Equals (211) TRect.Copy Declaration: Procedure TRect.Copy (R: TRect); Description: Assigns the rectangle R to the object. After the call to Copy, the rectangle R has been copied to the object that invoked Copy. Errors: None. See also: Assign (214) Program ex2 ; { Program to demonstrate TRect . Copy } Uses o b j e c t s ; Var ARect , BRect , CRect : TRect ; 211 11.4. TRECT begin ARect . Assign ( 1 0 , 1 0 , 2 0 , 2 0 ) ; BRect . Assign ( 1 5 , 1 5 , 2 5 , 2 5 ) ; CRect . Copy( ARect ) ; I f ARect . Equals ( CRect ) Then Writeln ( ' ARect equals CRect ' ) Else Writeln ( ' ARect does not equal CRect ! ' ) ; end . TRect.Union Declaration: Procedure TRect.Union (R: TRect); Description: Union enlarges the current rectangle so that it becomes the union of the current rectangle with the rectangle R. Errors: None. See also: Intersect (212) Program ex3 ; { Program to demonstrate TRect . Union } Uses o b j e c t s ; Var ARect , BRect , CRect : TRect ; begin ARect . Assign ( 1 0 , 1 0 , 2 0 , 2 0 ) ; BRect . Assign ( 1 5 , 1 5 , 2 5 , 2 5 ) ; { CRect i s union of ARect and BRect } CRect . Assign ( 1 0 , 1 0 , 2 5 , 2 5 ) ; { C a l c u l a t e i t e x p l i c i t l y } ARect . Union ( BRect ) ; I f ARect . Equals ( CRect ) Then Writeln ( ' ARect equals CRect ' ) Else Writeln ( ' ARect does not equal CRect ! ' ) ; end . TRect.Intersect Declaration: Procedure TRect.Intersect (R: TRect); Description: Intersect makes the intersection of the current rectangle with R. If the inter- section is empty, then the rectangle is set to the empty rectangle at coordinate (0,0). Errors: None. See also: Union (212) 212 11.4. TRECT Program ex4 ; { Program to demonstrate TRect . I n t e r s e c t } Uses o b j e c t s ; Var ARect , BRect , CRect : TRect ; begin ARect . Assign ( 1 0 , 1 0 , 2 0 , 2 0 ) ; BRect . Assign ( 1 5 , 1 5 , 2 5 , 2 5 ) ; { CRect i s i n t e r s e c t i o n of ARect and BRect } CRect . Assign ( 1 5 , 1 5 , 2 0 , 2 0 ) ; { C a l c u l a t e i t e x p l i c i t l y } ARect . I n t e r s e c t ( BRect ) ; I f ARect . Equals ( CRect ) Then Writeln ( ' ARect equals CRect ' ) Else Writeln ( ' ARect does not equal CRect ! ' ) ; BRect . Assign ( 2 5 , 2 5 , 3 0 , 3 0 ) ; Arect . I n t e r s e c t ( BRect ) ; I f ARect . Empty Then Writeln ( ' ARect i s empty ' ) ; end . TRect.Move Declaration: Procedure TRect.Move (ADX, ADY: Sw Integer); Description: Move moves the current rectangle along a vector with components (ADX,ADY). It adds ADX to the X-coordinate of both corner points, and ADY to both end points. Errors: None. See also: Grow (214) Program ex5 ; { Program to demonstrate TRect . Move } Uses o b j e c t s ; Var ARect , BRect : TRect ; begin ARect . Assign ( 1 0 , 1 0 , 2 0 , 2 0 ) ; ARect . Move( 5 , 5 ) ; // Brect should be where new ARect i s . BRect . Assign ( 1 5 , 1 5 , 2 5 , 2 5 ) ; I f ARect . Equals ( BRect ) Then Writeln ( ' ARect equals BRect ' ) Else 213 11.5. TOBJECT Writeln ( ' ARect does not equal BRect ! ' ) ; end . TRect.Grow Declaration: Procedure TRect.Grow (ADX, ADY: Sw Integer); Description: Grow expands the rectangle with an amount ADX in the X direction (both on the left and right side of the rectangle, thus adding a length 2*ADX to the width of the rectangle), and an amount ADY in the Y direction (both on the top and the bottom side of the rectangle, adding a length 2*ADY to the height of the rectangle. ADX and ADY can be negative. If the resulting rectangle is empty, it is set to the empty rectangle at (0,0). Errors: None. See also: Move (213). Program ex6 ; { Program to demonstrate TRect . Grow } Uses o b j e c t s ; Var ARect , BRect : TRect ; begin ARect . Assign ( 1 0 , 1 0 , 2 0 , 2 0 ) ; ARect . Grow ( 5 , 5 ) ; // Brect should be where new ARect i s . BRect . Assign ( 5 , 5 , 2 5 , 2 5 ) ; I f ARect . Equals ( BRect ) Then Writeln ( ' ARect equals BRect ' ) Else Writeln ( ' ARect does not equal BRect ! ' ) ; end . TRect.Assign Declaration: Procedure Trect.Assign (XA, YA, XB, YB: Sw Integer); Description: Assign sets the corner points of the rectangle to (XA,YA) and (Xb,Yb). Errors: None. See also: Copy (211) For an example, see TRect.Copy (211). 11.5 TObject The full declaration of the TObject type is: 214 11.5. TOBJECT TYPETObject = OBJECT CONSTRUCTOR Init; PROCEDURE Free; DESTRUCTOR Done;Virtual; END; PObject = ^TObject; TObject.Init Declaration: Constructor TObject.Init; Description: Instantiates a new object of type TObject. It fills the instance up with Zero bytes. Errors: None. See also: Free (215), Done (215) For an example, see Free (215) TObject.Free Declaration: Procedure TObject.Free; Description: Free calls the destructor of the object, and releases the memory occupied by the instance of the object. Errors: No checking is performed to see whether self is nil and whether the object is indeed allocated on the heap. See also: Init (215), Done (215) program ex7 ; { Program to demonstrate the TObject . Free c a l l } Uses Objects ; Var O : PObject ; begin Writeln ( ' Memavail : ' , Memavail ) ; // A l l o c a t e memory for object . O:=New( PObject , I n i t ) ; Writeln ( ' Memavail : ' , Memavail ) ; // Free memory of object . O . free ; Writeln ( ' Memavail : ' , Memavail ) ; end . TObject.Done Declaration: Destructor TObject.Done;Virtual; 215 11.6. TSTREAM Description: Done, the destructor of TObject does nothing. It is mainly intended to be used in the TObject.Free (215) method. The destructore Done does not free the memory occupied by the object. Errors: None. See also: Free (215), Init (215) program ex8 ; { Program to demonstrate the TObject . Done c a l l } Uses Objects ; Var O : PObject ; begin Writeln ( ' Memavail : ' , Memavail ) ; // A l l o c a t e memory for object . O:=New( PObject , I n i t ) ; Writeln ( ' Memavail : ' , Memavail ) ; O . Done ; Writeln ( ' Memavail : ' , Memavail ) ; end . 11.6 TStream The TStream object is the ancestor for all streaming objects, i.e. objects that have the capability to store and retrieve data. It defines a number of methods that are common to all objects that implement streaming, many of them are virtual, and are only implemented in the descendrnt types. Programs should not instantiate objects of type TStream directly, but instead in- stantiate a descendant type, such as TDosStream, TMemoryStream. This is the full declaration of the TStream object: TYPETStream = OBJECT (TObject) Status : Integer; { Stream status } ErrorInfo : Integer; { Stream error info } StreamSize: LongInt; { Stream current size } Position : LongInt; { Current position } FUNCTION Get: PObject; FUNCTION StrRead: PChar; FUNCTION GetPos: Longint; Virtual; FUNCTION GetSize: Longint; Virtual; FUNCTION ReadStr: PString; PROCEDURE Open (OpenMode: Word); Virtual; PROCEDURE Close; Virtual; PROCEDURE Reset; PROCEDURE Flush; Virtual; PROCEDURE Truncate; Virtual; 216 11.6. TSTREAM PROCEDURE Put (P: PObject); PROCEDURE StrWrite (P: PChar); PROCEDURE WriteStr (P: PString); PROCEDURE Seek (Pos: LongInt); Virtual; PROCEDURE Error (Code, Info: Integer); Virtual; PROCEDURE Read (Var Buf; Count: Sw_Word); Virtual; PROCEDURE Write (Var Buf; Count: Sw_Word); Virtual; PROCEDURE CopyFrom (Var S: TStream; Count: Longint); END; PStream = ^TStream; TStream.Get Declaration: Function TStream.Get : PObject; Description: Get reads an object definition from a stream, and returns a pointer to an instance of this object. Errors: On error, TStream.Status is set, and NIL is returned. See also: Put (221) Program ex9 ; { Program to demonstrate TStream . Get and TStream . Put } Uses Objects , MyObject ; { D e f i n i t i o n and r e g i s t r a t i o n of TMyObject } Var Obj : PMyObject ; S : PStream ; begin Obj :=New( PMyObject , I n i t ) ; Obj . S e t F i e l d ( $1111 ) ; Writeln ( ' F i e l d value : ' , Obj . G e t F i e l d ) ; { Since Stream i s an a b s t r a c t type , we i n s t a n t i a t e a TMemoryStream } S:=New( PMemoryStream , I n i t ( 1 0 0 , 1 0 ) ) ; S . Put ( Obj ) ; Writeln ( ' Disposing o b j e c t ' ) ; S . Seek ( 0 ) ; Dispose ( Obj , Done ) ; Writeln ( ' Reading o b j e c t ' ) ; Obj := PMyObject ( S . Get ) ; Writeln ( ' F i e l d Value : ' , Obj . G e t F i e l d ) ; Dispose ( Obj , Done ) ; end . TStream.StrRead Declaration: Function TStream.StrRead: PChar; Description: StrRead reads a string from the stream, allocates memory for it, and returns a pointer to a null-terminated copy of the string on the heap. Errors: On error, Nil is returned. 217 11.6. TSTREAM See also: StrWrite (221), ReadStr (219) Program ex10 ; {Program to demonstrate the TStream. StrRead TStream. StrWrite functions } Uses o b j e c t s ; Var P : PChar ; S : PStream ; begin P:= ' Constant Pchar s t r i n g ' ; Writeln ( ' Writing to stream : " ' , P, ' " ' ) ; S:=New( PMemoryStream , I n i t ( 1 0 0 , 1 0 ) ) ; S . StrWrite (P) ; S . Seek ( 0 ) ; P:= Nil ; P:=S . StrRead ; DisPose ( S , Done ) ; Writeln ( ' Read from stream : " ' , P, ' " ' ) ; Freemem(P, Strlen (P)+1); end . TStream.GetPos Declaration: TSTream.GetPos : Longint; Virtual; Description: If the stream's status is stOk, GetPos returns the current position in the stream. Otherwise it returns -1 Errors: -1 is returned if the status is an error condition. See also: Seek (222), GetSize (219) Program ex11 ; { Program to demonstrate the TStream . GetPos f u n c t i o n } Uses o b j e c t s ; Var L : String ; S : PStream ; begin L:= ' Some kind of s t r i n g ' ; S:=New( PMemoryStream , I n i t ( 1 0 0 , 1 0 ) ) ; Writeln ( ' Stream p o s i t i o n b e f o r e w r i t e : ' , S . GetPos ) ; S . WriteStr ( @L) ; Writeln ( ' Stream p o s i t i o n a f t e r w r i t e : ' , S . GetPos ) ; Dispose ( S , Done ) ; end . 218 11.6. TSTREAM TStream.GetSize Declaration: Function TStream.GetSize: Longint; Virtual; Description: If the stream's status is stOk then GetSize returns the size of the stream, otherwise it returns -1. Errors: -1 is returned if the status is an error condition. See also: Seek (222), GetPos (218) Program ex12 ; { Program to demonstrate the TStream . GetSize f u n c t i o n } Uses o b j e c t s ; Var L : String ; S : PStream ; begin L:= ' Some kind of s t r i n g ' ; S:=New( PMemoryStream , I n i t ( 1 0 0 , 1 0 ) ) ; Writeln ( ' Stream s i z e b e f o r e w r i t e : ' , S . GetSize ) ; S . WriteStr ( @L) ; Writeln ( ' Stream s i z e a f t e r w r i t e : ' , S . GetSize ) ; Dispose ( S , Done ) ; end . TStream.ReadStr Declaration: Function TStream.ReadStr: PString; Description: ReadStr reads a string from the stream, copies it to the heap and returns a pointer to this copy. The string is saved as a pascal string, and hence is NOT null termi- nated. Errors: On error (e.g. not enough memory), Nil is returned. See also: StrRead (217) Program ex13 ; {Program to demonstrate the TStream. ReadStr TStream. WriteStr functions } Uses o b j e c t s ; Var P : PString ; L : String ; S : PStream ; begin L:= ' Constant s t r i n g l i n e ' ; Writeln ( ' Writing to stream : " ' , L , ' " ' ) ; 219 11.6. TSTREAM S:=New( PMemoryStream , I n i t ( 1 0 0 , 1 0 ) ) ; S . WriteStr ( @L) ; S . Seek ( 0 ) ; P:=S . ReadStr ; L:=P ; DisposeStr (P) ; DisPose ( S , Done ) ; Writeln ( ' Read from stream : " ' , L , ' " ' ) ; end . TStream.Open Declaration: Procedure TStream.Open (OpenMode: Word); Virtual; Description: Open is an abstract method, that should be overridden by descendent objects. Since opening a stream depends on the stream's type this is not surprising. Errors: None. See also: Close (220), Reset (220) For an example, see TDosStream.Open (227). TStream.Close Declaration: Procedure TStream.Close; Virtual; Description: Close is an abstract method, that should be overridden by descendent objects. Since Closing a stream depends on the stream's type this is not surprising. Errors: None. See also: Open (220), Reset (220) for an example, see TDosStream.Open (227). TStream.Reset Declaration: PROCEDURE TStream.Reset; Description: Reset sets the stream's status to 0, as well as the ErrorInfo Errors: None. See also: Open (220), Close (220) TStream.Flush Declaration: Procedure TStream.Flush; Virtual; Description: Flush is an abstract method that should be overridden by descendent objects. It serves to enable the programmer to tell streams that implement a bu er to clear the bu er. Errors: None. 220 11.6. TSTREAM See also: Truncate (221) for an example, see TBufStream.Flush (230). TStream.Truncate Declaration: Procedure TStream.Truncate; Virtual; Description: Truncate is an abstract procedure that should be overridden by descendent ob- jects. It serves to enable the programmer to truncate the size of the stream to the current file position. Errors: None. See also: Seek (222) For an example, see TDosStream.Truncate (225). TStream.Put Declaration: Procedure TStream.Put (P: PObject); Description: Put writes the object pointed to by P. P should be non-nil. The object type must have been registered with RegisterType (207). After the object has been written, it can be read again with Get (217). Errors: No check is done whether P is Nil or not. Passing Nil will cause a run-time error 216 to be generated. If the object has not been registered, the status of the stream will be set to stPutError. See also: Get (217) For an example, see TStream.Get (217); TStream.StrWrite Declaration: Procedure TStream.StrWrite (P: PChar); Description: StrWrite writes the null-terminated string P to the stream. P can only be 65355 bytes long. Errors: None. See also: WriteStr (221), StrRead (217), ReadStr (219) For an example, see TStream.StrRead (217). TStream.WriteStr Declaration: Procedure TStream.WriteStr (P: PString); Description: StrWrite writes the pascal string pointed to by P to the stream. Errors: None. See also: StrWrite (221), StrRead (217), ReadStr (219) For an example, see TStream.ReadStr (219). 221 11.6. TSTREAM TStream.Seek Declaration: PROCEDURE TStream.Seek (Pos: LongInt); Virtual; Description: Seek sets the position to Pos. This position is counted from the beginning, and is zero based. (i.e. seeek(0) sets the position pointer on the first byte of the stream) Errors: If Pos is larger than the stream size, Status is set to StSeekError. See also: GetPos (218), GetSize (219) For an example, see TDosStream.Seek (226). TStream.Error Declaration: Procedure TStream.Error (Code, Info: Integer); Virtual; Description: Error sets the stream's status to Code and ErrorInfo to Info. If the StreamError procedural variable is set, Error executes it, passing Self as an argument. This method should not be called directly from a program. It is intended to be used in descendent objects. Errors: None. See also: TStream.Read Declaration: Procedure TStream.Read (Var Buf; Count: Sw Word); Virtual; Description: Read is an abstract method that should be overridden by descendent objects. Read reads Count bytes from the stream into Buf. It updates the position pointer, increasing it's value with Count. Buf must be large enough to contain Count bytes. Errors: No checking is done to see if Buf is large enough to contain Count bytes. See also: Write (223), ReadStr (219), StrRead (217) program ex18 ; { Program to demonstrate the TStream . Read method } Uses Objects ; Var Buf1 , Buf2 : Array [ 1 . . 1 0 0 0 ] of Byte ; I : l o n g i n t ; S : PMemorySTream ; begin For I :=1 to 1000 do Buf1 [ I ]:= Random(1000); Buf2 := Buf1 ; S:=New( PMemoryStream , I n i t ( 1 0 0 , 1 0 ) ) ; S . Write ( Buf1 , SizeOf ( Buf1 ) ) ; S . Seek ( 0 ) ; For I :=1 to 1000 do 222 11.6. TSTREAM Buf1 [ I ]:=0; S . Read( Buf1 , SizeOf ( Buf1 ) ) ; For I :=1 to 1000 do I f Buf1 [ I ]<>buf2 [ i ] then Writeln ( ' Buffer d i f f e r s at p o s i t i o n ' , I ) ; Dispose ( S , Done ) ; end . TStream.Write Declaration: Procedure TStream.Write (Var Buf; Count: Sw Word); Virtual; Description: Write is an abstract method that should be overridden by descendent objects. Write writes Count bytes to the stream from Buf. It updates the position pointer, increasing it's value with Count. Errors: No checking is done to see if Buf actually contains Count bytes. See also: Read (222), WriteStr (221), StrWrite (221) For an example, see TStream.Read (222). TStream.CopyFrom Declaration: Procedure TStream.CopyFrom (Var S: TStream; Count: Longint); Description: CopyFrom reads Count bytes from stream S and stores them in the current stream. It uses the Read (222) method to read the data, and the Write (223) method to write in the current stream. Errors: None. See also: Read (222), Write (223) Program ex19 ; { Program to demonstrate the TStream . CopyFrom f u n c t i o n } Uses o b j e c t s ; Var P : PString ; L : String ; S1 , S2 : PStream ; begin L:= ' Constant s t r i n g l i n e ' ; Writeln ( ' Writing to stream 1 : " ' , L , ' " ' ) ; S1:=New( PMemoryStream , I n i t ( 1 0 0 , 1 0 ) ) ; S2:=New( PMemoryStream , I n i t ( 1 0 0 , 1 0 ) ) ; S1 . WriteStr ( @L) ; S1 . Seek ( 0 ) ; Writeln ( ' Copying contents of stream 1 to stream 2' ) ; S2 . Copyfrom ( S1 , S1 . GetSize ) ; S2 . Seek ( 0 ) ; 223 11.7. TDOSSTREAM P:=S2 . ReadStr ; L:=P ; DisposeStr (P) ; Dispose ( S1 , Done ) ; Dispose ( S2 , Done ) ; Writeln ( ' Read from stream 2 : " ' , L , ' " ' ) ; end . 11.7 TDosStream TDosStream is a stream that stores it's contents in a file. it overrides a couple of methods of TSteam for this. In addition to the fields inherited from TStream (see section 11.6, page 216), there are some extra fields, that describe the file. (mainly the name and the OS file handle) No bu ering in memory is done when using TDosStream. All data are written directly to the file. For a stream that bu ers in memory, see section 11.8, page 228. Here is the full declaration of the TDosStream object: TYPETDosStream = OBJECT (TStream) Handle: THandle; { DOS file handle } FName : AsciiZ; { AsciiZ filename } CONSTRUCTOR Init (FileName: FNameStr; Mode: Word); DESTRUCTOR Done; Virtual; PROCEDURE Close; Virtual; PROCEDURE Truncate; Virtual; PROCEDURE Seek (Pos: LongInt); Virtual; PROCEDURE Open (OpenMode: Word); Virtual; PROCEDURE Read (Var Buf; Count: Sw_Word); Virtual; PROCEDURE Write (Var Buf; Count: Sw_Word); Virtual; END; PDosStream = ^TDosStream; TDosStream.Init Declaration: Constructor Init (FileName: FNameStr; Mode: Word); Description: Init instantiates an instance of TDosStream. The name of the file that contains (or will contain) the data of the stream is given in FileName. The Mode parameter determines whether a new file should be created and what access rights you have on the file. It can be one of the following constants: stCreateCreates a new file. stOpenReadRead access only. stOpenWriteWrite access only. stOpenRead and write access. Errors: On error, Status is set to stInitError, and ErrorInfo is set to the dos error code. 224 11.7. TDOSSTREAM See also: Done (225) For an example, see TDosStream.Truncate (225). TDosStream.Done Declaration: Destructor TDosStream.Done; Virtual; Description: Done closes the file if it was open and cleans up the instance of TDosStream. Errors: None. See also: Init (224), Close (225) for an example, see e.g. TDosStream.Truncate (225). TDosStream.Close Declaration: Pocedure TDosStream.Close; Virtual; Description: Close closes the file if it was open, and sets Handle to -1. Contrary to Done (225) it does not clean up the instance of TDosStream Errors: None. See also: TStream.Close (220), Init (224), Done (225) For an example, see TDosStream.Open (227). TDosStream.Truncate Declaration: Procedure TDosStream.Truncate; Virtual; Description: If the status of the stream is stOK, then Truncate tries to truncate the stream size to the current file position. Errors: If an error occurs, the stream's status is set to stError and ErrorInfo is set to the OS error code. See also: TStream.Truncate (221), GetSize (219) Program ex16 ; { Program to demonstrate the TStream . Truncate method } Uses Objects ; Var L : String ; P : PString ; S : PDosStream ; { Only one with Truncate implemented . } begin L:= ' Some constant s t r i n g ' ; { Buffer s i z e of 100 } S:=New( PDosStream , I n i t ( ' t e s t . dat ' , s t c r e a t e ) ) ; 225 11.7. TDOSSTREAM Writeln ( ' Writing "' , L , '" to stream with handle ' , S . Handle ) ; S . WriteStr ( @L) ; S . WriteStr ( @L) ; { Close c a l l s f l u s h f i r s t } S . Close ; S . Open ( stOpen ) ; Writeln ( ' Size of stream i s : ' , S . GetSize ) ; P:=S . ReadStr ; L:=P ; DisposeStr (P) ; Writeln ( ' Read "' , L , '" from stream with handle ' , S . Handle ) ; S . Truncate ; Writeln ( ' Truncated stream . Size i s : ' , S . GetSize ) ; S . Close ; Dispose ( S , Done ) ; end . TDosStream.Seek Declaration: Procedure TDosStream.Seek (Pos: LongInt); Virtual; Description: If the stream's status is stOK, then Seek sets the file position to Pos. Pos is a zero-based o set, counted from the beginning of the file. Errors: In case an error occurs, the stream's status is set to stSeekError, and the OS error code is stored in ErrorInfo. See also: TStream.Seek (222), GetPos (218) Program ex17 ; { Program to demonstrate the TStream . Seek method } Uses Objects ; Var L : String ; Marker : Word ; P : PString ; S : PDosStream ; begin L:= ' Some constant s t r i n g ' ; { Buffer s i z e of 100 } S:=New( PDosStream , I n i t ( ' t e s t . dat ' , s t c r e a t e ) ) ; Writeln ( ' Writing "' , L , '" to stream . ' ) ; S . WriteStr ( @L) ; Marker :=S . GetPos ; Writeln ( ' Set marker at ' , Marker ) ; L:= ' Some other constant S t r i n g ' ; Writeln ( ' Writing "' , L , '" to stream . ' ) ; S . WriteStr ( @L) ; S . Close ; S . Open ( stOpenRead ) ; Writeln ( ' Size of stream i s : ' , S . GetSize ) ; 226 11.7. TDOSSTREAM Writeln ( ' Seeking to marker ' ) ; S . Seek ( Marker ) ; P:=S . ReadStr ; L:=P ; DisposeStr (P) ; Writeln ( ' Read "' , L , '" from stream . ' ) ; S . Close ; Dispose ( S , Done ) ; end . TDosStream.Open Declaration: Procedure TDosStream.Open (OpenMode: Word); Virtual; Description: If the stream's status is stOK, and the stream is closed then Open re-opens the file stream with mode OpenMode. This call can be used after a Close (225) call. Errors: If an error occurs when re-opening the file, then Status is set to stOpenError, and the OS error code is stored in ErrorInfo See also: TStream.Open (220), Close (225) Program ex14 ; { Program to demonstrate the TStream . Close method } Uses Objects ; Var L : String ; P : PString ; S : PDosStream ; { Only one with Close implemented . } begin L:= ' Some constant s t r i n g ' ; S:=New( PDosStream , I n i t ( ' t e s t . dat ' , s t c r e a t e ) ) ; Writeln ( ' Writing "' , L , '" to stream with handle ' , S . Handle ) ; S . WriteStr ( @L) ; S . Close ; Writeln ( ' Closed stream . F i l e handle i s ' , S . Handle ) ; S . Open ( stOpenRead ) ; P:=S . ReadStr ; L:=P ; DisposeStr (P) ; Writeln ( ' Read "' , L , '" from stream with handle ' , S . Handle ) ; S . Close ; Dispose ( S , Done ) ; end . TDosStream.Read Declaration: Procedure TDosStream.Read (Var Buf; Count: Sw Word); Virtual; Description: If the Stream is open and the stream status is stOK then Read will read Count bytes from the stream and place them in Buf. 227 11.8. TBUFSTREAM Errors: In case of an error, Status is set to StReadError, and ErrorInfo gets the OS specific error, or 0 when an attempt was made to read beyond the end of the stream. See also: TStream.Read (222), Write (228) For an example, see TStream.Read (222). TDosStream.Write Declaration: Procedure TDosStream.Write (Var Buf; Count: Sw Word); Virtual; Description: If the Stream is open and the stream status is stOK then Write will write Count bytes from Buf and place them in the stream. Errors: In case of an error, Status is set to StWriteError, and ErrorInfo gets the OS specific error. See also: TStream.Write (223), Read (227) For an example, see TStream.Read (222). 11.8 TBufStream Bufstream implements a bu ered file stream. That is, all data written to the stream is written to memory first. Only when the bu er is full, or on explicit request, the data is written to disk. Also, when reading from the stream, first the bu er is checked if there is any unread data in it. If so, this is read first. If not the bu er is filled again, and then the data is read from the bu er. The size of the bu er is fixed and is set when constructing the file. This is useful if you need heavy throughput for your stream, because it speeds up operations. TYPETBufStream = OBJECT (TDosStream) LastMode: Byte; { Last buffer mode } BufSize : Sw_Word; { Buffer size } BufPtr : Sw_Word; { Buffer start } BufEnd : Sw_Word; { Buffer end } Buffer : PByteArray; { Buffer allocated } CONSTRUCTOR Init (FileName: FNameStr; Mode, Size: Word); DESTRUCTOR Done; Virtual; PROCEDURE Close; Virtual; PROCEDURE Flush; Virtual; PROCEDURE Truncate; Virtual; PROCEDURE Seek (Pos: LongInt); Virtual; PROCEDURE Open (OpenMode: Word); Virtual; PROCEDURE Read (Var Buf; Count: Sw_Word); Virtual; PROCEDURE Write (Var Buf; Count: Sw_Word); Virtual; END; PBufStream = ^TBufStream; 228 11.8. TBUFSTREAM TBufStream.Init Declaration: Constructor Init (FileName: FNameStr; Mode,Size: Word); Description: Init instantiates an instance of TBufStream. The name of the file that contains (or will contain) the data of the stream is given in FileName. The Mode parameter determines whether a new file should be created and what access rights you have on the file. It can be one of the following constants: stCreateCreates a new file. stOpenReadRead access only. stOpenWriteWrite access only. stOpenRead and write access. The Size parameter determines the size of the bu er that will be created. It should be di erent from zero. Errors: On error, Status is set to stInitError, and ErrorInfo is set to the dos error code. See also: TDosStream.Init (224), Done (229) For an example see TBufStream.Flush (230). TBufStream.Done Declaration: Destructor TBufStream.Done; Virtual; Description: Done flushes and closes the file if it was open and cleans up the instance of TBufStream. Errors: None. See also: TDosStream.Done (225), Init (229), Close (229) For an example see TBufStream.Flush (230). TBufStream.Close Declaration: Pocedure TBufStream.Close; Virtual; Description: Close flushes and closes the file if it was open, and sets Handle to -1. Contrary to Done (229) it does not clean up the instance of TBufStream Errors: None. See also: TStream.Close (220), Init (229), Done (229) For an example see TBufStream.Flush (230). 229 11.8. TBUFSTREAM TBufStream.Flush Declaration: Pocedure TBufStream.Flush; Virtual; Description: When the stream is in write mode, the contents of the bu er are written to disk, and the bu er position is set to zero. When the stream is in read mode, the bu er position is set to zero. Errors: Write errors may occur if the file was in write mode. see Write (231) for more info on the errors. See also: TStream.Close (220), Init (229), Done (229) Program ex15 ; { Program to demonstrate the TStream . Flush method } Uses Objects ; Var L : String ; P : PString ; S : PBufStream ; { Only one with Flush implemented . } begin L:= ' Some constant s t r i n g ' ; { Buffer s i z e of 100 } S:=New( PBufStream , I n i t ( ' t e s t . dat ' , s t c r e a t e , 1 0 0 ) ) ; Writeln ( ' Writing "' , L , '" to stream with handle ' , S . Handle ) ; S . WriteStr ( @L) ; { At t h i s moment , there i s no data on disk yet . } S . Flush ; { Now there i s . } S . WriteStr ( @L) ; { Close c a l l s f l u s h f i r s t } S . Close ; Writeln ( ' Closed stream . F i l e handle i s ' , S . Handle ) ; S . Open ( stOpenRead ) ; P:=S . ReadStr ; L:=P ; DisposeStr (P) ; Writeln ( ' Read "' , L , '" from stream with handle ' , S . Handle ) ; S . Close ; Dispose ( S , Done ) ; end . TBufStream.Truncate Declaration: Procedure TBufStream.Truncate; Virtual; Description: If the status of the stream is stOK, then Truncate tries to flush the bu er, and then truncates the stream size to the current file position. Errors: Errors can be those of Flush (230) or TDosStream.Truncate (225). See also: TStream.Truncate (221), TDosStream.Truncate (225), GetSize (219) For an example, see TDosStream.Truncate (225). 230 11.8. TBUFSTREAM TBufStream.Seek Declaration: Procedure TBufStream.Seek (Pos: LongInt); Virtual; Description: If the stream's status is stOK, then Seek sets the file position to Pos. Pos is a zero-based o set, counted from the beginning of the file. Errors: In case an error occurs, the stream's status is set to stSeekError, and the OS error code is stored in ErrorInfo. See also: TStream.Seek (222), GetPos (218) For an example, see TStream.Seek (222); TBufStream.Open Declaration: Procedure TBufStream.Open (OpenMode: Word); Virtual; Description: If the stream's status is stOK, and the stream is closed then Open re-opens the file stream with mode OpenMode. This call can be used after a Close (229) call. Errors: If an error occurs when re-opening the file, then Status is set to stOpenError, and the OS error code is stored in ErrorInfo See also: TStream.Open (220), Close (229) For an example, see TDosStream.Open (227). TBufStream.Read Declaration: Procedure TBufStream.Read (Var Buf; Count: Sw Word); Virtual; Description: If the Stream is open and the stream status is stOK then Read will read Count bytes from the stream and place them in Buf. Read will first try to read the data from the stream's internal bu er. If insu cient data is available, the bu er will be filled before contiunuing to read. This process is repeated until all needed data has been read. Errors: In case of an error, Status is set to StReadError, and ErrorInfo gets the OS specific error, or 0 when an attempt was made to read beyond the end of the stream. See also: TStream.Read (222), Write (231) For an example, see TStream.Read (222). TBufStream.Write Declaration: Procedure TBufStream.Write (Var Buf; Count: Sw Word); Virtual; Description: If the Stream is open and the stream status is stOK then Write will write Count bytes from Buf and place them in the stream. Write will first try to write the data to the stream's internal bu er. When the internal bu er is full, then the contents will be written to disk. This process is repeated until all data has been written. 231 11.9. TMEMORYSTREAM Errors: In case of an error, Status is set to StWriteError, and ErrorInfo gets the OS specific error. See also: TStream.Write (223), Read (231) For an example, see TStream.Read (222). 11.9 TMemoryStream The TMemoryStream object implements a stream that stores it's data in memory. The data is stored on the heap, with the possibility to specify the maximum amout of data, and the the size of the memory blocks being used. TYPETMemoryStream = OBJECT (TStream) BlkCount: Sw_Word; { Number of segments } BlkSize : Word; { Memory block size } MemSize : LongInt; { Memory alloc size } BlkList : PPointerArray; { Memory block list } CONSTRUCTOR Init (ALimit: Longint; ABlockSize: Word); DESTRUCTOR Done; Virtual; PROCEDURE Truncate; Virtual; PROCEDURE Read (Var Buf; Count: Sw_Word); Virtual; PROCEDURE Write (Var Buf; Count: Sw_Word); Virtual; END; PMemoryStream = ^TMemoryStream; TMemoryStream.Init Declaration: Constructor TMemoryStream.Init (ALimit: Longint; ABlockSize: Word); Description: Init instantiates a new TMemoryStream object. The memorystreamobject will initially allocate at least ALimit bytes memory, divided into memory blocks of size ABlockSize. The number of blocks needed to get to ALimit bytes is rounded up. By default, the number of blocks is 1, and the size of a block is 8192. This is selected if you specify 0 as the blocksize. Errors: If the stream cannot allocate the initial memory needed for the memory blocks, then the stream's status is set to stInitError. See also: Done (232) For an example, see e.g TStream.CopyFrom (223). TMemoryStream.Done Declaration: Destructor TMemoryStream.Done; Virtual; Description: Done releases the memory blocks used by the stream, and then cleans up the memory used by the stream object itself. Errors: None. See also: Init (232) For an example, see e.g TStream.CopyFrom (223). 232 11.9. TMEMORYSTREAM TMemoryStream.Truncate Declaration: Procedure TMemoryStream.Truncate; Virtual; Description: Truncate sets the size of the memory stream equal to the current position. It de-allocates any memory-blocks that are no longer needed, so that the new size of the stream is the current position in the stream, rounded up to the first multiple of the stream blocksize. Errors: If an error occurs during memory de-allocation, the stream's status is set to stError See also: TStream.Truncate (221) Program ex20 ; { Program to demonstrate the TMemoryStream . Truncate method } Uses Objects ; Var L : String ; P : PString ; S : PMemoryStream ; I , InitMem : Longint ; begin initMem :=Memavail ; L:= ' Some constant s t r i n g ' ; { Buffer s i z e of 100 } S:=New( PMemoryStream , I n i t ( 1 0 0 0 , 1 0 0 ) ) ; Writeln ( ' Free memory : ' , Memavail ) ; Writeln ( ' Writing 100 times "' , L , '" to stream . ' ) ; For I :=1 to 100 do S . WriteStr ( @L) ; Writeln ( ' F i n i s h e d . Free memory : ' , Memavail ) ; S . Seek ( 1 0 0 ) ; S . Truncate ; Writeln ( ' Truncated at byte 100. Free memory : ' , Memavail ) ; Dispose ( S , Done ) ; Writeln ( ' F i n i s h e d . Lost ' , InitMem-Memavail , ' Bytes . ' ) ; end . TMemoryStream.Read Declaration: Procedure Read (Var Buf; Count: Sw Word); Virtual; Description: Read reads Count bytes from the stream to Buf. It updates the position of the stream. Errors: If there is not enough data available, no data is read, and the stream's status is set to stReadError. See also: TStream.Read, Write (234) For an example, see TStream.Read (222). 233 11.10. TCOLLECTION TMemoryStream.Write Declaration: Procedure Write (Var Buf; Count: Sw Word); Virtual; Description: Write copies Count bytes from Buf to the stream. It updates the position of the stream. If not enough memory is available to hold the extra Count bytes, then the stream will try to expand, by allocating as much blocks with size BlkSize (as specified in the constuctor call Init (232)) as needed. Errors: If the stream cannot allocate more memory, then the status is set to stWriteError See also: TStream.Write (223), Read (233) For an example, see TStream.Read (222). 11.10 TCollection The TCollection object manages a collection of pointers or objects. It also provides a series of methods to manipulate these pointers or objects. Whether or not objects are used depends on the kind of calls you use. ALl kinds come in 2 flavors, one for objects, one for pointers. This is the full declaration of the TCollection object: TYPETItemList = Array [0..MaxCollectionSize - 1] Of Pointer; PItemList = ^TItemList; TCollection = OBJECT (TObject) Items: PItemList; { Item list pointer } Count: Sw_Integer; { Item count } Limit: Sw_Integer; { Item limit count } Delta: Sw_Integer; { Inc delta size } Constructor Init (ALimit, ADelta: Sw_Integer); Constructor Load (Var S: TStream); Destructor Done; Virtual; Function At (Index: Sw_Integer): Pointer; Function IndexOf (Item: Pointer): Sw_Integer; Virtual; Function GetItem (Var S: TStream): Pointer; Virtual; Function LastThat (Test: Pointer): Pointer; Function FirstThat (Test: Pointer): Pointer; Procedure Pack; Procedure FreeAll; Procedure DeleteAll; Procedure Free (Item: Pointer); Procedure Insert (Item: Pointer); Virtual; Procedure Delete (Item: Pointer); Procedure AtFree (Index: Sw_Integer); Procedure FreeItem (Item: Pointer); Virtual; Procedure AtDelete (Index: Sw_Integer); Procedure ForEach (Action: Pointer); Procedure SetLimit (ALimit: Sw_Integer); Virtual; Procedure Error (Code, Info: Integer); Virtual; 234 11.10. TCOLLECTION Procedure AtPut (Index: Sw_Integer; Item: Pointer); Procedure AtInsert (Index: Sw_Integer; Item: Pointer); Procedure Store (Var S: TStream); Procedure PutItem (Var S: TStream; Item: Pointer); Virtual; END; PCollection = ^TCollection; TCollection.Init Declaration: Constructor TCollection.Init (ALimit, ADelta: Sw Integer); Description: Init initializes a new instance of a collection. It sets the (initial) maximum number of items in the collection to ALimit. ADelta is the increase size : The number of memory places that will be allocatiod in case ALimit is reached, and another element is added to the collection. Errors: None. See also: Load (235), Done (236) For an example, see TCollection.ForEach (245). TCollection.Load Declaration: Constructor TCollection.Load (Var S: TStream); Description: Load initializes a new instance of a collection. It reads from stream S the item count, the item limit count, and the increase size. After that, it reads the specified number of items from the stream. Errors: Errors returned can be those of GetItem (238). See also: Init (235), GetItem (238), Done (236). Program ex22 ; { Program to demonstrate the T C o l l e c t i o n . Load method } Uses Objects , MyObject ; { For TMyObject d e f i n i t i o n and r e g i s t r a t i o n } Var C : P C o l l e c t i o n ; M : PMyObject ; I : Longint ; S : PMemoryStream ; begin C:=New( P C o l l e c t i o n , I n i t ( 1 0 0 , 1 0 ) ) ; For I :=1 to 100 do begin M:=New( PMyObject , I n i t ) ; M . S e t F i e l d (100- I ) ; C . Insert (M) ; end ; Writeln ( ' I n s e r t e d ' , C . Count , ' o b j e c t s ' ) ; S:=New( PMemorySTream , I n i t ( 1 0 0 0 , 1 0 ) ) ; 235 11.10. TCOLLECTION C . Store ( S ); C . F r e e A l l ; Dispose (C, Done ) ; S . Seek ( 0 ) ; C . Load ( S ); Writeln ( ' Read ' , C . Count , ' o b j e c t s from stream . ' ) ; Dispose ( S , Done ) ; Dispose (C, Done ) ; end . TCollection.Done Declaration: Destructor TCollection.Done; Virtual; Description: Done frees all objects in the collection, and then releases all memory occupied by the instance. Errors: None. See also: Init (235), FreeAll (240) For an example, see TCollection.ForEach (245). TCollection.At Declaration: Function TCollection.At (Index: Sw Integer): Pointer; Description: At returns the item at position Index. Errors: If Index is less than zero or larger than the number of items in the collection, seeplErrorTCollection.Error is called with coIndexError and Index as arguments, resulting in a run-time error. See also: Insert (243) Program ex23 ; { Program to demonstrate the T C o l l e c t i o n . At method } Uses Objects , MyObject ; { For TMyObject d e f i n i t i o n and r e g i s t r a t i o n } Var C : P C o l l e c t i o n ; M : PMyObject ; I : Longint ; begin C:=New( P C o l l e c t i o n , I n i t ( 1 0 0 , 1 0 ) ) ; For I :=1 to 100 do begin M:=New( PMyObject , I n i t ) ; M . S e t F i e l d (100- I ) ; C . Insert (M) ; end ; For I :=0 to C . Count -1 do 236 11.10. TCOLLECTION begin M:=C . At( I ) ; Writeln ( ' Object ' , i , ' has f i e l d : ' ,M . G e t F i e l d ) ; end ; C . F r e e A l l ; Dispose (C, Done ) ; end . TCollection.IndexOf Declaration: Function TCollection.IndexOf (Item: Pointer): Sw Integer; Virtual; Description: IndexOf returns the index of Item in the collection. If Item isn't present in the collection, -1 is returned. Errors: See also: Program ex24 ; { Program to demonstrate the T C o l l e c t i o n . IndexOf method } Uses Objects , MyObject ; { For TMyObject d e f i n i t i o n and r e g i s t r a t i o n } Var C : P C o l l e c t i o n ; M, Keep : PMyObject ; I : Longint ; begin Randomize ; C:=New( P C o l l e c t i o n , I n i t ( 1 0 0 , 1 0 ) ) ; Keep := Nil ; For I :=1 to 100 do begin M:=New( PMyObject , I n i t ) ; M . S e t F i e l d ( I -1); I f Random<0.1 then Keep :=M; C . Insert (M) ; end ; I f Keep=Nil then begin Writeln ( ' Please run again . No o b j e c t s e l e c t e d ' ) ; Halt ( 1 ) ; end ; Writeln ( ' S e l e c t e d o b j e c t has f i e l d : ' , Keep . G e t F i e l d ) ; Write ( ' S e l e c t e d o b j e c t has index : ' , C . IndexOf ( Keep ) ) ; Writeln ( ' should match i t ' ' s f i e l d . ' ) ; C . F r e e A l l ; Dispose (C, Done ) ; end . 237 11.10. TCOLLECTION TCollection.GetItem Declaration: Function TCollection.GetItem (Var S: TStream): Pointer; Virtual; Description: GetItem reads a single item o the stream S, and returns a pointer to this item. This method is used internally by the Load method, and should not be used directly. Errors: Possible errors are the ones from TStream.Get (217). See also: TStream.Get (217), seeplStoreTCollection.Store TCollection.LastThat Declaration: Function TCollection.LastThat (Test: Pointer): Pointer; Description: This function returns the last item in the collection for which Test returns a non- nil result. Test is a function that accepts 1 argument: a pointer to an object, and that returns a pointer as a result. Errors: None. See also: FirstThat (239) Program ex21 ; { Program to demonstrate the T C o l l e c t i o n . Foreach method } Uses Objects , MyObject ; { For TMyObject d e f i n i t i o n and r e g i s t r a t i o n } Var C : P C o l l e c t i o n ; M : PMyObject ; I : Longint ; Function CheckField ( Dummy: Pointer ; P : PMyObject ) : Longint ; begin I f P . G e t F i e l d <56 then C h e c k f i e l d :=1 else CheckField :=0; end ; begin C:=New( P C o l l e c t i o n , I n i t ( 1 0 0 , 1 0 ) ) ; For I :=1 to 100 do begin M:=New( PMyObject , I n i t ) ; M . S e t F i e l d ( I ) ; C . Insert (M) ; end ; Writeln ( ' I n s e r t e d ' , C . Count , ' o b j e c t s ' ) ; Writeln ( ' Last one fo r which F i e l d <56 has index ( should be 5 4 ) : ' , C . IndexOf (C . LastThat ( @CheckField ) ) ) ; C . F r e e A l l ; Dispose (C, Done ) ; end . 238 11.10. TCOLLECTION TCollection.FirstThat Declaration: Function TCollection.FirstThat (Test: Pointer): Pointer; Description: This function returns the first item in the collection for which Test returns a non- nil result. Test is a function that accepts 1 argument: a pointer to an object, and that returns a pointer as a result. Errors: None. See also: LastThat (238) Program ex21 ; { Program to demonstrate the T C o l l e c t i o n . F i r s t T h a t method } Uses Objects , MyObject ; { For TMyObject d e f i n i t i o n and r e g i s t r a t i o n } Var C : P C o l l e c t i o n ; M : PMyObject ; I : Longint ; Function CheckField ( Dummy: Pointer ; P : PMyObject ) : Longint ; begin I f P . G e t F i e l d >56 then C h e c k f i e l d :=1 else CheckField :=0; end ; begin C:=New( P C o l l e c t i o n , I n i t ( 1 0 0 , 1 0 ) ) ; For I :=1 to 100 do begin M:=New( PMyObject , I n i t ) ; M . S e t F i e l d ( I ) ; C . Insert (M) ; end ; Writeln ( ' I n s e r t e d ' , C . Count , ' o b j e c t s ' ) ; Writeln ( ' f i r s t one fo r which F i e l d >56 has index ( should be 5 6 ) : ' , C . IndexOf (C . F i r s t T h a t ( @CheckField ) ) ) ; C . F r e e A l l ; Dispose (C, Done ) ; end . TCollection.Pack Declaration: Procedure TCollection.Pack; Description: Pack removes all Nil pointers from the collection, and adjusts Count to reflect this change. No memory is freed as a result of this call. In order to free any memory, you can call SetLimit with an argument of Count after a call to Pack. Errors: None. 239 11.10. TCOLLECTION See also: SetLimit (246) Program ex21 ; { Program to demonstrate the T C o l l e c t i o n . F i r s t T h a t method } Uses Objects , MyObject ; { For TMyObject d e f i n i t i o n and r e g i s t r a t i o n } Var C : P C o l l e c t i o n ; M : PMyObject ; I : Longint ; Function CheckField ( Dummy: Pointer ; P : PMyObject ) : Longint ; begin I f P . G e t F i e l d >56 then C h e c k f i e l d :=1 else CheckField :=0; end ; begin C:=New( P C o l l e c t i o n , I n i t ( 1 0 0 , 1 0 ) ) ; For I :=1 to 100 do begin M:=New( PMyObject , I n i t ) ; M . S e t F i e l d ( I ) ; C . Insert (M) ; end ; Writeln ( ' I n s e r t e d ' , C . Count , ' o b j e c t s ' ) ; Writeln ( ' f i r s t one fo r which F i e l d >56 has index ( should be 5 6 ) : ' , C . IndexOf (C . F i r s t T h a t ( @CheckField ) ) ) ; C . F r e e A l l ; Dispose (C, Done ) ; end . TCollection.FreeAll Declaration: Procedure TCollection.FreeAll; Description: FreeAll calls the destructor of each object in the collection. It doesn't release any memory occumpied by the collection itself, but it does set Count to zero. Errors: See also: DeleteAll (241), FreeItem (244) Program ex28 ; { Program to demonstrate the T C o l l e c t i o n . F r e e A l l method } Uses Objects , MyObject ; { For TMyObject d e f i n i t i o n and r e g i s t r a t i o n } Var C : P C o l l e c t i o n ; 240 11.10. TCOLLECTION M : PMyObject ; I , InitMem : Longint ; begin Randomize ; C:=New( P C o l l e c t i o n , I n i t ( 1 2 0 , 1 0 ) ) ; InitMem :=Memavail ; Writeln ( ' I n i t i a l memory : ' , InitMem ) ; For I :=1 to 100 do begin M:=New( PMyObject , I n i t ) ; M . S e t F i e l d ( I -1); C . Insert (M) ; end ; Writeln ( ' Added 100 Items . Memory a v a i l a b l e : ' , Memavail ) ; Write ( ' Lost : ' , Initmem-Memavail , ' bytes . ' ) ; Write ( ' ( Should be 100 ' , SizeOF ( TMyObject ) ) ; Writeln ( '=' ,100 SizeOf ( TMyObject ) , ' ) ' ) ; C . F r e e A l l ; Writeln ( ' Freed a l l o b j e c t s . Memory a v a i l a b l e : ' , Memavail ) ; Writeln ( ' Lost : ' , Initmem-Memavail , ' bytes . ' ) ; Dispose (C, Done ) ; end . TCollection.DeleteAll Declaration: Procedure TCollection.DeleteAll; Description: DeleteAll deletes all elements from the collection. It just sets the Count variable to zero. Contrary to FreeAll (240), DeletAll doesn't call the destructor of the objects. Errors: None. See also: FreeAll (240), Delete (243) Program ex29 ; { Program to demonstrate the TCollection . DeleteAll method Compare with example 2 8 , where F r e e A l l i s used . } Uses Objects , MyObject ; { For TMyObject d e f i n i t i o n and r e g i s t r a t i o n } Var C : P C o l l e c t i o n ; M : PMyObject ; I , InitMem : Longint ; begin Randomize ; C:=New( P C o l l e c t i o n , I n i t ( 1 2 0 , 1 0 ) ) ; InitMem :=Memavail ; Writeln ( ' I n i t i a l memory : ' , InitMem ) ; 241 11.10. TCOLLECTION For I :=1 to 100 do begin M:=New( PMyObject , I n i t ) ; M . S e t F i e l d ( I -1); C . Insert (M) ; end ; Writeln ( ' Added 100 Items . Memory a v a i l a b l e : ' , Memavail ) ; Write ( ' Lost : ' , Initmem-Memavail , ' bytes . ' ) ; Write ( ' ( Should be 100 ' , SizeOF ( TMyObject ) ) ; Writeln ( '=' ,100 SizeOf ( TMyObject ) , ' ) ' ) ; C . D e l e t e A l l ; Writeln ( ' Deleted a l l o b j e c t s . Memory a v a i l a b l e : ' , Memavail ) ; Writeln ( ' Lost : ' , Initmem-Memavail , ' bytes . ' ) ; Dispose (C, Done ) ; end . TCollection.Free Declaration: Procedure TCollection.Free (Item: Pointer); Description: Free Deletes Item from the collection, and calls the destructor Done of the object. Errors: If the Item is not in the collection, Error will be called with coIndexError. See also: FreeItem (244), Program ex30 ; { Program to demonstrate the T C o l l e c t i o n . Free method } Uses Objects , MyObject ; { For TMyObject d e f i n i t i o n and r e g i s t r a t i o n } Var C : P C o l l e c t i o n ; M : PMyObject ; I , InitMem : Longint ; begin Randomize ; C:=New( P C o l l e c t i o n , I n i t ( 1 2 0 , 1 0 ) ) ; InitMem :=Memavail ; Writeln ( ' I n i t i a l memory : ' , InitMem ) ; For I :=1 to 100 do begin M:=New( PMyObject , I n i t ) ; M . S e t F i e l d ( I -1); C . Insert (M) ; end ; Writeln ( ' Added 100 Items . Memory a v a i l a b l e : ' , Memavail ) ; Write ( ' Lost : ' , Initmem-Memavail , ' bytes . ' ) ; Write ( ' ( Should be 100 ' , SizeOF ( TMyObject ) ) ; Writeln ( '=' ,100 SizeOf ( TMyObject ) , ' ) ' ) ; With C do While Count >0 do Free ( At( Count -1)); Writeln ( ' Freed a l l o b j e c t s . Memory a v a i l a b l e : ' , Memavail ) ; 242 11.10. TCOLLECTION Writeln ( ' Lost : ' , Initmem-Memavail , ' bytes . ' ) ; Dispose (C, Done ) ; end . TCollection.Insert Declaration: Procedure TCollection.Insert (Item: Pointer); Virtual; Description: Insert inserts Item in the collection. TCollection inserts this item at the end, but descendent objects may insert it at another place. Errors: None. See also: AtInsert (247), AtPut (247), TCollection.Delete Declaration: Procedure TCollection.Delete (Item: Pointer); Description: Delete deletes Item from the collection. It doesn't call the item's destructor, though. For this the Free (242) call is provided. Errors: If the Item is not in the collection, Error will be called with coIndexError. See also: AtDelete (245),Free (242) Program ex31 ; { Program to demonstrate the T C o l l e c t i o n . Delete method } Uses Objects , MyObject ; { For TMyObject d e f i n i t i o n and r e g i s t r a t i o n } Var C : P C o l l e c t i o n ; M : PMyObject ; I , InitMem : Longint ; begin Randomize ; C:=New( P C o l l e c t i o n , I n i t ( 1 2 0 , 1 0 ) ) ; InitMem :=Memavail ; Writeln ( ' I n i t i a l memory : ' , InitMem ) ; For I :=1 to 100 do begin M:=New( PMyObject , I n i t ) ; M . S e t F i e l d ( I -1); C . Insert (M) ; end ; Writeln ( ' Added 100 Items . Memory a v a i l a b l e : ' , Memavail ) ; Write ( ' Lost : ' , Initmem-Memavail , ' bytes . ' ) ; Write ( ' ( Should be 100 ' , SizeOF ( TMyObject ) ) ; Writeln ( '=' ,100 SizeOf ( TMyObject ) , ' ) ' ) ; With C do While Count >0 do Delete ( At( Count -1)); Writeln ( ' Freed a l l o b j e c t s . Memory a v a i l a b l e : ' , Memavail ) ; Writeln ( ' Lost : ' , Initmem-Memavail , ' bytes . ' ) ; 243 11.10. TCOLLECTION Dispose (C, Done ) ; end . TCollection.AtFree Declaration: Procedure TCollection.AtFree (Index: Sw Integer); Description: AtFree deletes the item at position Index in the collection, and calls the item's destructor if it is not Nil. Errors: If Index isn't valid then Error (246) is called with CoIndexError. See also: Free (242), AtDelete (245) Program ex32 ; { Program to demonstrate the T C o l l e c t i o n . AtFree method } Uses Objects , MyObject ; { For TMyObject d e f i n i t i o n and r e g i s t r a t i o n } Var C : P C o l l e c t i o n ; M : PMyObject ; I , InitMem : Longint ; begin Randomize ; C:=New( P C o l l e c t i o n , I n i t ( 1 2 0 , 1 0 ) ) ; InitMem :=Memavail ; Writeln ( ' I n i t i a l memory : ' , InitMem ) ; For I :=1 to 100 do begin M:=New( PMyObject , I n i t ) ; M . S e t F i e l d ( I -1); C . Insert (M) ; end ; Writeln ( ' Added 100 Items . Memory a v a i l a b l e : ' , Memavail ) ; Write ( ' Lost : ' , Initmem-Memavail , ' bytes . ' ) ; Write ( ' ( Should be 100 ' , SizeOF ( TMyObject ) ) ; Writeln ( '=' ,100 SizeOf ( TMyObject ) , ' ) ' ) ; With C do While Count >0 do AtFree ( Count -1); Writeln ( ' Freed a l l o b j e c t s . Memory a v a i l a b l e : ' , Memavail ) ; Writeln ( ' Lost : ' , Initmem-Memavail , ' bytes . ' ) ; Dispose (C, Done ) ; end . TCollection.FreeItem Declaration: Procedure TCollection.FreeItem (Item: Pointer); Virtual; Description: FreeItem calls the destructor of Item if it is not nil. This function is used internally by the TCollection object, and should not be called directly. 244 11.10. TCOLLECTION Errors: None. See also: Free (244), seeplAtFreeTCollection.AtFree TCollection.AtDelete Declaration: Procedure TCollection.AtDelete (Index: Sw Integer); Description: AtDelete deletes the pointer at position Index in the collection. It doesn't call the object's destructor. Errors: If Index isn't valid then Error (246) is called with CoIndexError. See also: Delete (243) Program ex33 ; { Program to demonstrate the T C o l l e c t i o n . AtDelete method } Uses Objects , MyObject ; { For TMyObject d e f i n i t i o n and r e g i s t r a t i o n } Var C : P C o l l e c t i o n ; M : PMyObject ; I , InitMem : Longint ; begin Randomize ; C:=New( P C o l l e c t i o n , I n i t ( 1 2 0 , 1 0 ) ) ; InitMem :=Memavail ; Writeln ( ' I n i t i a l memory : ' , InitMem ) ; For I :=1 to 100 do begin M:=New( PMyObject , I n i t ) ; M . S e t F i e l d ( I -1); C . Insert (M) ; end ; Writeln ( ' Added 100 Items . Memory a v a i l a b l e : ' , Memavail ) ; Write ( ' Lost : ' , Initmem-Memavail , ' bytes . ' ) ; Write ( ' ( Should be 100 ' , SizeOF ( TMyObject ) ) ; Writeln ( '=' ,100 SizeOf ( TMyObject ) , ' ) ' ) ; With C do While Count >0 do AtDelete ( Count -1); Writeln ( ' Freed a l l o b j e c t s . Memory a v a i l a b l e : ' , Memavail ) ; Writeln ( ' Lost : ' , Initmem-Memavail , ' bytes . ' ) ; Dispose (C, Done ) ; end . TCollection.ForEach Declaration: Procedure TCollection.ForEach (Action: Pointer); Description: ForEach calls Action for each element in the collection, and passes the element as an argument to Action. Action is a procedural type variable that accepts a pointer as an argument. 245 11.10. TCOLLECTION Errors: None. See also: FirstThat (239), LastThat (238) Program ex21 ; { Program to demonstrate the T C o l l e c t i o n . Foreach method } Uses Objects , MyObject ; { For TMyObject d e f i n i t i o n and r e g i s t r a t i o n } Var C : P C o l l e c t i o n ; M : PMyObject ; I : Longint ; Procedure P r i n t F i e l d ( Dummy: Pointer ; P : PMyObject ) ; begin Writeln ( ' F i e l d : ' , P . G e t F i e l d ) ; end ; begin C:=New( P C o l l e c t i o n , I n i t ( 1 0 0 , 1 0 ) ) ; For I :=1 to 100 do begin M:=New( PMyObject , I n i t ) ; M . S e t F i e l d (100- I ) ; C . Insert (M) ; end ; Writeln ( ' I n s e r t e d ' , C . Count , ' o b j e c t s ' ) ; C . ForEach ( @ P r i n t F i e l d ) ; C . F r e e A l l ; Dispose (C, Done ) ; end . TCollection.SetLimit Declaration: Procedure TCollection.SetLimit (ALimit: Sw Integer); Virtual; Description: SetLimit sets the maximum number of elements in the collection. ALimit must not be less than Count, and should not be larger than MaxCollectionSize Errors: None. See also: Init (235) For an example, see Pack (239). TCollection.Error Declaration: Procedure TCollection.Error (Code, Info: Integer); Virtual; Description: Error is called by the various TCollection methods in case of an error condition. The default behaviour is to make a call to RunError with an error of 212-Code. This method can be overridden by descendent objects to implement a di erent error-handling. 246 11.10. TCOLLECTION Errors: See also: Abstract (207) TCollection.AtPut Declaration: Procedure TCollection.AtPut (Index: Sw Integer; Item: Pointer); Description: AtPut sets the element at position Index in the collection to Item. Any previous value is overwritten. Errors: If Index isn't valid then Error (246) is called with CoIndexError. See also: For an example, see Pack (239). TCollection.AtInsert Declaration: Procedure TCollection.AtInsert (Index: Sw Integer; Item: Pointer); Description: AtInsert inserts Item in the collection at position Index, shifting all elements by one position. In case the current limit is reached, the collection will try to expand with a call to SetLimit Errors: If Index isn't valid then Error (246) is called with CoIndexError. If the collection fails to expand, then coOverFlow is passd to Error. See also: Insert (243) Program ex34 ; { Program to demonstrate the T C o l l e c t i o n . A t I n s e r t method } Uses Objects , MyObject ; { For TMyObject d e f i n i t i o n and r e g i s t r a t i o n } Var C : P C o l l e c t i o n ; M : PMyObject ; I : Longint ; Procedure P r i n t F i e l d ( Dummy: Pointer ; P : PMyObject ) ; begin Writeln ( ' F i e l d : ' , P . G e t F i e l d ) ; end ; begin Randomize ; C:=New( P C o l l e c t i o n , I n i t ( 1 2 0 , 1 0 ) ) ; Writeln ( ' I n s e r t i n g 100 r e c o r d s at random p l a c e s . ' ) ; For I :=1 to 100 do begin M:=New( PMyObject , I n i t ) ; M . S e t F i e l d ( I -1); 247 11.11. TSORTEDCOLLECTION I f I =1 then C . Insert (M) else With C do A t I n s e r t (Random( Count ) , M) ; end ; Writeln ( ' Values : ' ) ; C . Foreach ( @ P r i n t F i e l d ) ; Dispose (C, Done ) ; end . TCollection.Store Declaration: Procedure TCollection.Store (Var S: TStream); Description: Store writes the collection to the stream S. It does this by writeing the current Count, Limit and Delta to the stream, and then writing each item to the stream. The contents of the stream are then suitable for instantiating another collection with Load (235). Errors: Errors returned are those by TStream.Put (221). See also: Load (235), PutItem (248) For an example, see seeplLoadTCollection.Load. TCollection.PutItem Declaration: Procedure TCollection.PutItem (Var S: TStream; Item: Pointer); Virtual; Description: PutItem writes Item to stream S. This method is used internaly by the TCollection object, and should not be called directly. Errors: Errors are those returned by TStream.Put (221). See also: Store (248), GetItem (238). 11.11 TSortedCollection TSortedCollection is an abstract class, implementing a sorted collection. You should never use an instance of TSortedCollection directly, instead you should declare a descendent type, and override the Compare (250) method. Because the collection is ordered, TSortedCollection overrides some TCollection methods, to provide faster routines for lookup. The Compare (250) method decides how elements in the collection should be ordered. Since TCollection has no way of knowing how to order pointers, you must override the compare method. Additionally, TCollection provides a means to filter out duplicates. if you set Duplicates to False (the default) then duplicates will not be allowed. Here is the complete declaration of TSortedCollection 248 11.11. TSORTEDCOLLECTION TYPETSortedCollection = OBJECT (TCollection) Duplicates: Boolean; { Duplicates flag } Constructor Init (ALimit, ADelta: Sw_Integer); Constructor Load (Var S: TStream); Function KeyOf (Item: Pointer): Pointer; Virtual; Function IndexOf (Item: Pointer): Sw_Integer; Virtual; Function Compare (Key1, Key2: Pointer): Sw_Integer; Virtual; Function Search (Key: Pointer; Var Index: Sw_Integer): Boolean;Virtual; Procedure Insert (Item: Pointer); Virtual; Procedure Store (Var S: TStream); END; PSortedCollection = ^TSortedCollection; In the subsequent examples, the following descendent of TSortedCollection is used: Unit MySortC ; Interface Uses Objects ; Type PMySortedCollection = TMySortedCollection ; TMySortedCollection = Object ( T S o r t e d C o l l e c t i o n ) Function Compare ( Key1 , Key2 : Pointer ) : Sw integer ; v i r t u a l ; end ; Implementation Uses MyObject ; Function TMySortedCollection . Compare ( Key1 , Key2 : Pointer ) : sw integer ; begin Compare := PMyobject ( Key1 ) . G e t F i e l d - PMyObject ( Key2 ) . G e t F i e l d ; end ; end . TSortedCollection.Init Declaration: Constructor TSortedCollection.Init (ALimit, ADelta: Sw Integer); Description: Init calls the inherited constuctor (see TCollection.Init (235)) and sets the Duplicates flag to false. You should not call this method directly, since TSortedCollection is a abstract class. Instead, the descendent classes should call it via the inherited keyword. Errors: None. See also: Load (250), Done (236) For an example, see 249 11.11. TSORTEDCOLLECTION TSortedCollection.Load Declaration: Constructor Load (Var S: TStream); Description: Load calls the inherited constuctor (see TCollection.Load (235)) and reads the Duplicates flag from the stream.. You should not call this method directly, since TSortedCollection is a abstract class. Instead, the descendent classes should call it via the inherited keyword. Errors: None. See also: Init (249), Done (236) For an example, see TCollection.Load (235). TSortedCollection.KeyOf Declaration: Function TSortedCollection.KeyOf (Item: Pointer): Pointer; Virtual; Description: KeyOf returns the key associated with Item. TSortedCollection returns the item itself as the key, descendent objects can override this method to calculate a (unique) key based on the item passed (such as hash values). Keys are used to sort the objects, they are used to search and sort the items in the collection. If descendent types override this method then it allows possibly for faster search/sort methods based on keys rather than on the objects themselves. Errors: None. See also: IndexOf (250), Compare (250). TSortedCollection.IndexOf Declaration: Function TSortedCollection.IndexOf (Item: Pointer): Sw Integer; Virtual; Description: IndexOf returns the index of Item in the collection. It searches for the object based on it's key. If duplicates are allowed, then it returns the index of last object that matches Item. In case Item is not found in the collection, -1 is returned. Errors: None. See also: Search (251), Compare (250). For an example, see TCollection.IndexOf (237) TSortedCollection.Compare Declaration: Function TSortedCollection.Compare (Key1, Key2: Pointer): Sw Integer; Virtual; Description: Compare is an abstract method that should be overridden by descendent objects in order to compare two items in the collection. This method is used in the Search (251) method and in the Insert (252) method to determine the ordering of the objects. The function should compare the two keys of items and return the following function results: 250 11.11. TSORTEDCOLLECTION Result ¡ 0If Key1 is logically before Key2 (Key1Key2) Errors: An 'abstract run-time error' will be generated if you call TSortedCollection.Compare directly. See also: IndexOf (250), Search (251) Unit MySortC ; Interface Uses Objects ; Type PMySortedCollection = TMySortedCollection ; TMySortedCollection = Object ( T S o r t e d C o l l e c t i o n ) Function Compare ( Key1 , Key2 : Pointer ) : Sw integer ; v i r t u a l ; end ; Implementation Uses MyObject ; Function TMySortedCollection . Compare ( Key1 , Key2 : Pointer ) : sw integer ; begin Compare := PMyobject ( Key1 ) . G e t F i e l d - PMyObject ( Key2 ) . G e t F i e l d ; end ; end . TSortedCollection.Search Declaration: Function TSortedCollection.Search (Key: Pointer; Var Index: Sw Integer): Boolean;Virtual; Description: Search looks for the item with key Key and returns the position of the item (if present) in the collection in Index. Instead of a linear search as TCollection does, TSortedCollection uses a binary search based on the keys of the objects. It uses the Compare (250) function to implement this search. If the item is found, Search returns True, otherwise False is returned. Errors: None. See also: IndexOf (237). Program ex36 ; { Program to demonstrate the T S o r t e d C o l l e c t i o n . I n s e r t method } 251 11.11. TSORTEDCOLLECTION Uses Objects , MyObject , MySortC ; { For TMyObject , TMySortedCollection d e f i n i t i o n and r e g i s t r a t i o n } Var C : P S o r t e d C o l l e c t i o n ; M : PMyObject ; I : Longint ; Procedure P r i n t F i e l d ( Dummy: Pointer ; P : PMyObject ) ; begin Writeln ( ' F i e l d : ' , P . G e t F i e l d ) ; end ; begin Randomize ; C:=New( PMySortedCollection , I n i t ( 1 2 0 , 1 0 ) ) ; C . D u p l i c a t e s := True ; Writeln ( ' I n s e r t i n g 100 r e c o r d s at random p l a c e s . ' ) ; For I :=1 to 100 do begin M:=New( PMyObject , I n i t ) ; M . S e t F i e l d (Random( 1 0 0 ) ) ; C . Insert (M) end ; M:=New( PMyObject , I n i t ) ; Repeat ; Write ( ' Value to search f or (-1 stops ) : ' ) ; read ( I ) ; I f I <>-1 then begin M . S e t F i e l d ( i ) ; I f Not C . Search ( M, I ) then Writeln ( ' No such value found ' ) else begin Write ( ' Value ' , PMyObject (C . At( I ) ) . G e t F i e l d ) ; Writeln ( ' p r e s e n t at p o s i t i o n ' , I ) ; end ; end ; Until I =-1; Dispose (M, Done ) ; Dispose (C, Done ) ; end . TSortedCollection.Insert Declaration: Procedure TSortedCollection.Insert (Item: Pointer); Virtual; Description: Insert inserts an item in the collection at the correct position, such that the collection is ordered at all times. You should never use Atinsert (247), since then the collection ordering is not guaranteed. If Item is already present in the collection, and Duplicates is False, the item will 252 11.11. TSORTEDCOLLECTION not be inserted. Errors: None. See also: AtInsert (247) Program ex35 ; { Program to demonstrate the T S o r t e d C o l l e c t i o n . I n s e r t method } Uses Objects , MyObject , MySortC ; { For TMyObject , TMySortedCollection d e f i n i t i o n and r e g i s t r a t i o n } Var C : P S o r t e d C o l l e c t i o n ; M : PMyObject ; I : Longint ; Procedure P r i n t F i e l d ( Dummy: Pointer ; P : PMyObject ) ; begin Writeln ( ' F i e l d : ' , P . G e t F i e l d ) ; end ; begin Randomize ; C:=New( PMySortedCollection , I n i t ( 1 2 0 , 1 0 ) ) ; Writeln ( ' I n s e r t i n g 100 r e c o r d s at random p l a c e s . ' ) ; For I :=1 to 100 do begin M:=New( PMyObject , I n i t ) ; M . S e t F i e l d (Random( 1 0 0 ) ) ; C . Insert (M) end ; Writeln ( ' Values : ' ) ; C . Foreach ( @ P r i n t F i e l d ) ; Dispose (C, Done ) ; end . TSortedCollection.Store Declaration: Procedure TSortedCollection.Store (Var S: TStream); Description: Store writes the collection to the stream S. It does this by calling the inherited TCollection.Store (248), and then writing the Duplicates flag to the stream. After a Store, the collection can be loaded from the stream with the constructor Load (250) Errors: Errors can be those of TStream.Put (221). See also: Load (250) For an example, see TCollection.Load (235). 253 11.12. TSTRINGCOLLECTION 11.12 TStringCollection The TStringCollection object manages a sorted collection of pascal strings. To this end, it overrides the Compare (250) method of TSortedCollection, and it introduces methods to read/write strings from a stream. Here is the full declaration of the TStringCollection object: TYPETStringCollection = OBJECT (TSortedCollection) Function GetItem (Var S: TStream): Pointer; Virtual; Function Compare (Key1, Key2: Pointer): Sw_Integer; Virtual; Procedure FreeItem (Item: Pointer); Virtual; Procedure PutItem (Var S: TStream; Item: Pointer); Virtual; END; PStringCollection = ^TStringCollection; TStringCollection.GetItem Declaration: Function TStringCollection.GetItem (Var S: TStream): Pointer; Virtual; Description: GetItem reads a string from the stream S and returns a pointer to it. It doesn't insert the string in the collection. This method is primarily introduced to be able to load and store the collection from and to a stream. Errors: The errors returned are those of TStream.ReadStr (219). See also: PutItem (255) TStringCollection.Compare Declaration: Function TStringCollection.Compare (Key1, Key2: Pointer): Sw Integer; Virtual; Description: TStringCollection overrides the Compare function so it compares the two keys as if they were pointers to strings. The compare is done case sensitive. It returns the following results: -1if the first string is alphabetically earlier than the second string. 0if the two strings are equal. 1if the first string is alphabetically later than the second string. Errors: None. See also: TSortedCollection.Compare (250) Program ex37 ; { Program to demonstrate the T S t r i n g C o l l e c t i o n . Compare method } Uses Objects ; Var C : P S t r i n g C o l l e c t i o n ; S : String ; 254 11.13. TSTRCOLLECTION I : l o n g i n t ; begin Randomize ; C:=New( P S t r i n g C o l l e c t i o n , I n i t ( 1 2 0 , 1 0 ) ) ; C . D u p l i c a t e s := True ; { D u p l i c a t e s allowed } Writeln ( ' I n s e r t i n g 100 r e c o r d s at random p l a c e s . ' ) ; For I :=1 to 100 do begin Str (Random( 1 0 0 ) , S ) ; S:= ' S t r i n g with value ' +S ; C . Insert ( NewStr( S ) ) ; end ; For I :=0 to 98 do With C do I f Compare ( At( i ) , At( I +1))=0 then Writeln ( ' D u p l i ca t e s t r i n g found at p o s i t i o n ' , i ) ; Dispose (C, Done ) ; end . TStringCollection.FreeItem Declaration: Procedure TStringCollection.FreeItem (Item: Pointer); Virtual; Description: TStringCollection overrides FreeItem so that the string pointed to by Item is disposed from memory. Errors: None. See also: TCollection.FreeItem (244) TStringCollection.PutItem Declaration: Procedure TStringCollection.PutItem (Var S: TStream; Item: Pointer); Virtual; Description: PutItem writes the string pointed to by Item to the stream S. This method is primarily used in the Load and Store methods, and should not be used directly. Errors: Errors are those of TStream.WriteStr (221). See also: GetItem (254) 11.13 TStrCollection The TStrCollection object manages a sorted collection of null-terminated strings (pchar strings). To this end, it overrides the Compare (250) method of TSortedCollection, and it introduces methods to read/write strings from a stream. Here is the full declaration of the TStrCollection object: TYPETStrCollection = OBJECT (TSortedCollection) 255 11.13. TSTRCOLLECTION Function Compare (Key1, Key2: Pointer): Sw_Integer; Virtual; Function GetItem (Var S: TStream): Pointer; Virtual; Procedure FreeItem (Item: Pointer); Virtual; Procedure PutItem (Var S: TStream; Item: Pointer); Virtual; END; PStrCollection = ^TStrCollection; TStrCollection.GetItem Declaration: Function TStrCollection.GetItem (Var S: TStream): Pointer; Virtual; Description: GetItem reads a null-terminated string from the stream S and returns a pointer to it. It doesn't insert the string in the collection. This method is primarily introduced to be able to load and store the collection from and to a stream. Errors: The errors returned are those of TStream.StrRead (217). See also: PutItem (257) TStrCollection.Compare Declaration: Function TStrCollection.Compare (Key1, Key2: Pointer): Sw Integer; Virtual; Description: TStrCollection overrides the Compare function so it compares the two keys as if they were pointers to strings. The compare is done case sensitive. It returns -1if the first string is alphabetically earlier than the second string. 0if the two strings are equal. 1if the first string is alphabetically later than the second string. Errors: None. See also: TSortedCollection.Compare (250) Program ex38 ; { Program to demonstrate the T S t r C o l l e c t i o n . Compare method } Uses Objects , S t r i n g s ; Var C : P S t r C o l l e c t i o n ; S : String ; I : l o n g i n t ; P : Pchar ; begin Randomize ; C:=New( P S t r C o l l e c t i o n , I n i t ( 1 2 0 , 1 0 ) ) ; C . D u p l i c a t e s := True ; { D u p l i c a t e s allowed } Writeln ( ' I n s e r t i n g 100 r e c o r d s at random p l a c e s . ' ) ; For I :=1 to 100 do begin 256 11.14. TUNSORTEDSTRCOLLECTION Str (Random( 1 0 0 ) , S ) ; S:= ' S t r i n g with value ' +S ; P:= S t r A l l o c ( Length ( S)+1); C . Insert ( StrPCopy (P, S ) ) ; end ; For I :=0 to 98 do With C do I f Compare ( At( I ) , At( I +1))=0 then Writeln ( ' D u p l i c a t e s t r i n g found at p o s i t i o n ' , I ) ; Dispose (C, Done ) ; end . TStrCollection.FreeItem Declaration: Procedure TStrCollection.FreeItem (Item: Pointer); Virtual; Description: TStrCollection overrides FreeItem so that the string pointed to by Item is dis- posed from memory. Errors: None. See also: TCollection.FreeItem (244) TStrCollection.PutItem Declaration: Procedure TStrCollection.PutItem (Var S: TStream; Item: Pointer); Virtual; Description: PutItem writes the string pointed to by Item to the stream S. This method is primarily used in the Load and Store methods, and should not be used directly. Errors: Errors are those of TStream.StrWrite (221). See also: GetItem (256) 11.14 TUnSortedStrCollection The TUnSortedStrCollection object manages an unsorted list of objects. To this end, it overrides the TSortedCollection.Insert (252) method to add strings at the end of the collection, rather than in the alphabetically correct position. Take care, the Search (251) and IndexOf (237) methods will not work on an unsorted string collection. Here is the full declaration of the TUnsortedStrCollection object: TYPETUnSortedStrCollection = OBJECT (TStringCollection) Procedure Insert (Item: Pointer); Virtual; END; PUnSortedStrCollection = ^TUnSortedStrCollection; 257 11.15. TRESOURCECOLLECTION TUnSortedStrCollection.Insert Declaration: Procedure TUnSortedStrCollection.Insert (Item: Pointer); Virtual; Description: Insert inserts a string at the end of the collection, instead of on it's alphabetical place, resulting in an unsorted collection of strings. Errors: See also: Program ex39 ; { Program to demonstrate the T U n s o r t e d S t r C o l l e c t i o n . I n s e r t method } Uses Objects , S t r i n g s ; Var C : P U n s o r t e d S t r C o l l e c t i o n ; S : String ; I : l o n g i n t ; P : Pchar ; begin Randomize ; C:=New( P U n s o r t e d S t r C o l l e c t i o n , I n i t ( 1 2 0 , 1 0 ) ) ; Writeln ( ' I n s e r t i n g 100 r e c o r d s at random p l a c e s . ' ) ; For I :=1 to 100 do begin Str (Random( 1 0 0 ) , S ) ; S:= ' S t r i n g with value ' +S ; P:= S t r A l l o c ( Length ( S)+1); C . Insert ( StrPCopy (P, S ) ) ; end ; For I :=0 to 99 do Writeln ( I : 2 , ' : ' , PChar (C . At( i ) ) ) ; Dispose (C, Done ) ; end . 11.15 TResourceCollection A TResourceCollection manages a collection of resource names. It stores the position and the size of a resource, as well as the name of the resource. It stores these items in records that look like this: TYPETResourceItem = packed RECORD Posn: LongInt; Size: LongInt; Key : String; End; PResourceItem = ^TResourceItem; It overrides some methods of TStringCollection in order to accomplish this. 258 11.15. TRESOURCECOLLECTION Remark that the TResourceCollection manages the names of the resources and their assiciated positions and sizes, it doesn't manage the resources themselves. Here is the full declaration of the TResourceCollection object: TYPETResourceCollection = OBJECT (TStringCollection) Function KeyOf (Item: Pointer): Pointer; Virtual; Function GetItem (Var S: TStream): Pointer; Virtual; Procedure FreeItem (Item: Pointer); Virtual; Procedure PutItem (Var S: TStream; Item: Pointer); Virtual; END; PResourceCollection = ^TResourceCollection; TResourceCollection.KeyOf Declaration: Function TResourceCollection.KeyOf (Item: Pointer): Pointer; Virtual; Description: KeyOf returns the key of an item in the collection. For resources, the key is a pointer to the string with the resource name. Errors: None. See also: TStringCollection.Compare (254) TResourceCollection.GetItem Declaration: Function TResourceCollection.GetItem (Var S: TStream): Pointer; Virtual; Description: GetItem reads a resource item from the stream S. It reads the position, size and name from the stream, in that order. It DOES NOT read the resource itself from the stream. The resulting item is not inserted in the collection. This call is manly for internal use by the TCollection.Load (235) method. Errors: Errors returned are those by TStream.Read (222) See also: TCollection.Load (235), TStream.Read (222) TResourceCollection.FreeItem Declaration: Procedure TResourceCollection.FreeItem (Item: Pointer); Virtual; Description: FreeItem releases the memory occupied by Item. It de-allocates the name, and then the resourceitem record. It does NOT remove the item from the collection. Errors: None. See also: TCollection.FreeItem (244) 259 11.16. TRESOURCEFILE TResourceCollection.PutItem Declaration: Procedure TResourceCollection.PutItem (Var S: TStream; Item: Pointer); Virtual; Description: PutItem writes Item to the stream S. It does this by writing the position and size and name of the resource item to the stream. This method is used primarily by the Store (248) method. Errors: Errors returned are those by TStream.Write (223). See also: Store (248) 11.16 TResourceFile TYPETResourceFile = OBJECT (TObject) Stream : PStream; { File as a stream } Modified: Boolean; { Modified flag } Constructor Init (AStream: PStream); Destructor Done; Virtual; Function Count: Sw_Integer; Function KeyAt (I: Sw_Integer): String; Function Get (Key: String): PObject; Function SwitchTo (AStream: PStream; Pack: Boolean): PStream; Procedure Flush; Procedure Delete (Key: String); Procedure Put (Item: PObject; Key: String); END; PResourceFile = ^TResourceFile; TResourceFile Fields TResourceFile has the following fields: Stream contains the (file) stream that has the executable image and the resources. It can be initialized by the Init (260) constructor call. Modified is set to True if one of the resources has been changed. It is set by the SwitchTo (260), Delete (262) and Put (262) methods. Calling Flush (262) will clear the Modified flag. TResourceFile.Init Declaration: Constructor TResourceFile.Init (AStream: PStream); Description: Init instantiates a new instance of a TResourceFile object. If AStream is not nil then it is considered as a stream describing an executable image on disk. Init will try to position the stream on the start of the resources section, and read all resources from the stream. Errors: None. See also: Done (261) 260 11.16. TRESOURCEFILE TResourceFile.Done Declaration: Destructor TResourceFile.Done; Virtual; Description: Done cleans up the instance of the TResourceFile Object. If Stream was specified at initialization, then Stream is disposed of too. Errors: None. See also: Init (260) TResourceFile.Count Declaration: Function TResourceFile.Count: Sw Integer; Description: Count returns the number of resources. If no resources were read, zero is returned. Errors: None. See also: Init (260) TResourceFile.KeyAt Declaration: Function TResourceFile.KeyAt (I: Sw Integer): String; Description: KeyAt returns the key (the name) of the I-th resource. Errors: In case I is invalid, TCollection.Error will be executed. See also: Get (261) TResourceFile.Get Declaration: Function TResourceFile.Get (Key: String): PObject; Description: Get returns a pointer to a instance of a resource identified by Key. If Key cannot be found in the list of resources, then Nil is returned. Errors: Errors returned may be those by TStream.Get See also: TResourceFile.SwitchTo Declaration: Function TResourceFile.SwitchTo (AStream: PStream; Pack: Boolean): PStream; Description: SwitchTo switches to a new stream to hold the resources in. AStream will be the new stream after the call to SwitchTo. If Pack is true, then all the known resources will be copied from the current stream to the new stream (AStream). If Pack is False, then only the current resource is copied. The return value is the value of the original stream: Stream. The Modified flag is set as a consequence of this call. Errors: Errors returned can be those of TStream.Read (222) and TStream.Write (223). See also: Flush (262) 261 11.17. TSTRINGLIST TResourceFile.Flush Declaration: Procedure TResourceFile.Flush; Description: If the Modified flag is set to True, then Flush writes the resources to the stream Stream. It sets the Modified flag to true after that. Errors: Errors can be those by TStream.Seek (222) and TStream.Write (223). See also: SwitchTo (261) TResourceFile.Delete Declaration: Procedure TResourceFile.Delete (Key: String); Description: Delete deletes the resource identified by Key from the collection. It sets the Modified flag to true. Errors: None. See also: Flush (262) TResourceFile.Put Declaration: Procedure TResourceFile.Put (Item: PObject; Key: String); Description: Put sets the resource identified by Key to Item. If no such resource exists, a new one is created. The item is written to the stream. Errors: Errors returned may be those by TStream.Put (221) and TStream.Seek See also: Get (261) 11.17 TStringList A TStringList object can be used to read a collection of strings stored in a stream. If you register this object with the RegisterType (207) function, you cannot register the TStrListMaker object. This is the public declaration of the TStringList object: TYPETStrIndexRec = Packed RECORD Key, Count, Offset: Word; END; TStrIndex = Array [0..9999] Of TStrIndexRec; PStrIndex = ^TStrIndex; TStringList = OBJECT (TObject) Constructor Load (Var S: TStream); Destructor Done; Virtual; Function Get (Key: Sw_Word): String; END; PStringList = ^TStringList; 262 11.18. TSTRLISTMAKER TStringList.Load Declaration: Constructor TstringList.Load (Var S: TStream); Description: The Load constructor reads the TStringList object from the stream S. It also reads the descriptions of the strings from the stream. The string descriptions are stored as an array of TstrIndexrec records, where each record describes a string on the stream. These records are kept in memory. Errors: If an error occurs, a stream error is triggered. See also: Done (263) TStringList.Done Declaration: Destructor TstringList.Done; Virtual; Description: The Done destructor frees the memory occupied by the string descriptions, and destroys the object. Errors: None. See also: Load (263), TObject.Done (215) TStringList.Get Declaration: Function TStringList.Get (Key: Sw Word): String; Description: Get reads the string with key Key from the list of strings on the stream, and returns this string. If there is no string with such a key, an empty string is returned. Errors: If no string with key Key is found, an empty string is returned. A stream error may result if the stream doesn't contain the needed strings. See also: TStrListMaker.Put (264) 11.18 TStrListMaker The TStrListMaker object can be used to generate a stream with strings, which can be read with the TStringList object. If you register this object with the RegisterType (207) function, you cannot register the TStringList object. This is the public declaration of the TStrListMaker object: TYPETStrListMaker = OBJECT (TObject) Constructor Init (AStrSize, AIndexSize: Sw_Word); Destructor Done; Virtual; Procedure Put (Key: SwWord; S: String); Procedure Store (Var S: TStream); END; PStrListMaker = ^TStrListMaker; 263 11.18. TSTRLISTMAKER TStrListMaker.Init Declaration: Constructor TStrListMaker.Init (AStrSize, AIndexSize: SwWord); Description: The Init constructor creates a new instance of the TstrListMaker object. It allocates AStrSize bytes on the heap to hold all the strings you wish to store. It also allocates enough room for AIndexSize key description entries (of the type TStrIndexrec). AStrSize must be large enough to contain all the strings you wish to store. If not enough memory is allocated, other memory will be overwritten. The same is true for AIndexSize : maximally AIndexSize strings can be written to the stream. Errors: None. See also: TObject.Init (215), Done (264) TStrListMaker.Done Declaration: Destructor TStrListMaker.Done; Virtual; Description: The Done destructor de-allocates the memory for the index description records and the string data, and then destroys the object. Errors: None. See also: TObject.Done (215), Init (264) TStrListMaker.Put Declaration: Procedure TStrListMaker.Put (Key: Sw Word; S: String); Description: Put adds they string S with key Key to the collection of strings. This action doesn't write the string to a stream. To write the strings to the stream, see the Store (264) method. Errors: None. See also: Store (264). TStrListMaker.Store Declaration: Procedure TStrListMaker.Store (Var S: TStream); Description: Store writes the collection of strings to the stream S. The collection can then be read with the TStringList object. Errors: A stream error may occur when writing the strings to the stream. See also: TStringList.Load (263), Put (264). 264 Chapter 12 The PRINTER unit. This chapter describes the PRINTER unit for Free Pascal. It was written for dos by Florian kl¨ampfl, and it was written for linux by Micha¨el Van Canneyt. Its basic functionality is the same for both systems. The chapter is divided in 2 sections: * The first section lists types, constants and variables from the interface part of the unit. * The second section describes the functions defined in the unit. 12.1 Types, Constants and variables : varlst : text; Lst is the standard printing device. On linux, Lst is set up using AssignLst('/tmp/PID.lst'). You can change this behaviour at compile time, setting the DefFile constant. 12.2 Procedures and functions AssignLst Declaration: Procedure AssignLst ( Var F : text; ToFile : string[255]); Description: linux only. Assigns to F a printing device. ToFile is a string with the following form: * '|filename options' : This sets up a pipe with the program filename, with the given options, such as in the popen() call. * 'filename' : Prints to file filename. Filename can contain the string 'PID' (No Quotes), which will be replaced by the PID of your program. When closing lst, the file will be sent to lpr and deleted. (lpr should be in PATH) *'filename|' Idem as previous, only the file is NOT sent to lpr, nor is it deleted. (useful for opening /dev/printer or for later printing) Errors: Errors are reported in Linuxerror. 265 12.2. PROCEDURES AND FUNCTIONS See also: lpr (1) program t e s t p r n ; uses p r i n t e r ; var i : i n t e g e r ; f : text ; begin writeln ( ' Test of p r i n t e r unit ' ) ; writeln ( ' Writing to l s t . . . ' ) ; for i :=1 to 80 do writeln ( l s t , ' This i s l i n e ' , i , ' . ' #13); c l o s e ( l s t ) ; writeln ( ' Done . ' ) ; { $ i f d e f l i n u x } writeln ( ' Writing to pipe . . . ' ) ; a s s i g n l s t ( f , ' | / usr / bin / l p r -m' ) ; rewrite ( f ) ; for i :=1 to 80 do writeln ( f , ' This i s l i n e ' , i , ' . ' #13); c l o s e ( f ) ; writeln ( ' Done . ' ) { $ e n d i f } end . 266 Chapter 13 The SOCKETS unit. This chapter describes the SOCKETS unit for Free Pascal. it was written for linux by Micha¨el Van Canneyt. The chapter is divided in 2 sections: * The first section lists types, constants and variables from the interface part of the unit. * The second section describes the functions defined in the unit. 13.1 Types, Constants and variables : The following constants identify the di erent socket types, as needed in the Socket (277) call. SOCK_STREAM = 1; { stream (connection) socket } SOCK_DGRAM = 2; { datagram (conn.less) socket } SOCK_RAW = 3; { raw socket } SOCK_RDM = 4; { reliably-delivered message } SOCK_SEQPACKET = 5; { sequential packet socket } SOCK_PACKET =10; The following constants determine the socket domain, they are used in the Socket (277) call. AF_UNSPEC = 0; AF_UNIX = 1; { Unix domain sockets } AF_INET = 2; { Internet IP Protocol } AF_AX25 = 3; { Amateur Radio AX.25 } AF_IPX = 4; { Novell IPX } AF_APPLETALK = 5; { Appletalk DDP } AF_NETROM = 6; { Amateur radio NetROM } AF_BRIDGE = 7; { Multiprotocol bridge } AF_AAL5 = 8; { Reserved for Werner's ATM } AF_X25 = 9; { Reserved for X.25 project } AF_INET6 = 10; { IP version 6 } AF_MAX = 12; The following constants determine the protocol family, they are used in the Socket (277) call. 267 13.2. FUNCTIONS AND PROCEDURES PF_UNSPEC = AF_UNSPEC; PF_UNIX = AF_UNIX; PF_INET = AF_INET; PF_AX25 = AF_AX25; PF_IPX = AF_IPX; PF_APPLETALK = AF_APPLETALK; PF_NETROM = AF_NETROM; PF_BRIDGE = AF_BRIDGE; PF_AAL5 = AF_AAL5; PF_X25 = AF_X25; PF_INET6 = AF_INET6; PF_MAX = AF_MAX; The following types are used to store di erent kinds of eddresses for the Bind (270), Recv (275) and Send (275) calls. TSockAddr = packed Record family:word; data :array [0..13] of char; end; TUnixSockAddr = packed Record family:word; path:array[0..108] of char; end; TInetSockAddr = packed Record family:Word; port :Word; addr :Cardinal; pad :array [1..8] of byte; end; The following type is returned by the SocketPair (277) call. TSockArray = Array[1..2] of Longint; 13.2 Functions and Procedures Accept Declaration: Function Accept (Sock:Longint;Var Addr;Var Addrlen:Longint) : Longint; Description: Accept accepts a connection from a socket Sock, which was listening for a con- nection. If a connection is accepted, a file descriptor is returned. On error -1 is returned. The returned socket may NOT be used to accept more connections. The original socket remains open. The Accept call fills the address of the connecting entity in Addr, and sets its length in Addrlen. Addr should be pointing to enough space, and Addrlen should be set to the amount of space available, prior to the call. Errors: On error, -1 is returned, and errors are reported in SocketError, and include the following: SYS EBADFThe socket descriptor is invalid. SYS ENOTSOCKThe descriptor is not a socket. 268 13.2. FUNCTIONS AND PROCEDURES SYS EOPNOTSUPPThe socket type doesn't support the Listen operation. SYS EFAULTAddr points outside your address space. SYS EWOULDBLOCKThe requested operation would block the process. See also: Listen (274), Connect (271) Program s e r v e r ; { Program to test Sockets unit by Michael van Canneyt and Peter Vreman Server Version , F i r s t Run sock svr to l e t i t c r e a t e a socket and then s o c k c l i to connect to that socket } uses Linux , Sockets ; const SPath=' ServerSoc ' ; VarFromName : string ; Buffer : st r ing [ 2 5 5 ] ; S : Longint ; Sin , Sout : Text ; procedure p e r r o r ( const S : st ri ng ) ; begin writeln ( S , So cketE rr or ) ; halt ( 1 0 0 ) ; end ; begin S:= Socket ( AF UNIX, SOCK STREAM, 0 ) ; i f So cketE rr or <>0 then Perror ( ' Server : Socket : ' ) ; UnLink ( SPath ) ; i f not Bind ( S , SPath ) then PError ( ' Server : Bind : ' ) ; i f not L i s t e n ( S , 1 ) then PError ( ' Server : L i s t e n : ' ) ; Writeln ( ' Waiting fo r Connect from C l i e n t , run now s o c k c l i in an other tty ' ) ; i f not Accept ( S , FromName , Sin , Sout ) then PError ( ' Server : Accept : ' ) ; Reset ( Sin ) ; ReWrite ( Sout ) ; Writeln ( Sout , ' Message From Server ' ) ; Flush ( SOut ) ; while not eof ( sin ) do begin Readln ( Sin , Buffer ) ; Writeln ( ' Server : read : ' , b u f f e r ) ; end ; Unlink ( SPath ) ; 269 13.2. FUNCTIONS AND PROCEDURES end . Accept Declaration: Function Accept (Sock:longint;var addr:string;var SockIn,SockOut:text) : Boolean; Description: This is an alternate form of the Accept (268) command. It is equivalent to subse- quently calling the regular Accept (268) function and the Sock2Text (277) function. The function returns True if successfull, False otherwise. Errors: The errors are those of Accept (268). See also: Accept (268) Accept Declaration: Function Accept (Sock:longint;var addr:string;var SockIn,SockOut:File) : Boolean; Description: This is an alternate form of the Accept (268) command. It is equivalent to subse- quently calling the regular Accept (268) function and the Sock2File (276) function. The Addr parameter contains the name of the unix socket file to be opened. The function returns True if successfull, False otherwise. Errors: The errors are those of Accept (268). See also: Accept (268) Accept Declaration: Function Accept (Sock:longint;var addr:TInetSockAddr;var SockIn,SockOut:File) : Boolean; Description: This is an alternate form of the Accept (268) command. It is equivalent to subse- quently calling the regular Accept (268) function and the Sock2File (276) function. The Addr parameter contains the parameters of the internet socket that should be opened. The function returns True if successfull, False otherwise. Errors: The errors are those of Accept (268). See also: Accept (268) Bind Declaration: Function Bind (Sock:Longint;Var Addr;AddrLen:Longint) : Boolean; Description: Bind binds the socket Sock to address Addr. Addr has length Addrlen. The function returns True if the call was succesful, False if not. Errors: Errors are returned in SocketError and include the following: SYS EBADFThe socket descriptor is invalid. SYS EINVALThe socket is already bound to an address, SYS EACCESSAddress is protected and you don't have permission to open it. 270 13.2. FUNCTIONS AND PROCEDURES More arrors can be found in the Unix man pages. See also: Socket (277) Bind Declaration: Function Bind (Sock:longint;const addr:string) : boolean; Description: This is an alternate form of the Bind command. This form of the Bind command is equivalent to subsequently calling Str2UnixSockAddr (277) and the regular Bind (270) function. The function returns True if successfull, False otherwise. Errors: Errors are those of the regular Bind (270) command. See also: Bind (270) Connect Declaration: Function Connect (Sock:Longint;Var Addr;Addrlen:Longint) : Longint; Description: Connect opens a connection to a peer, whose address is described by Addr. AddrLen contains the length of the address. The type of Addr depends on the kind of connec- tion you're trying to make, but is generally one of TSockAddr or TUnixSockAddr. The Connect function returns a file descriptor if the call was successfull, -1 in case of error. Errors: On error, -1 is returned and errors are reported in SocketError. See also: Listen (274), Bind (270),Accept (268) Program C l i e n t ; { Program to test Sockets unit by Michael van Canneyt and Peter Vreman C l i e n t Version , F i r s t Run sock svr to l e t i t c r e a t e a socket and then s o c k c l i to connect to that socket } uses Sockets , Linux ; procedure PError ( const S : s tr in g ) ; begin writeln ( S , Soc ket Erro r ) ; halt ( 1 0 0 ) ; end ; VarSaddr : String [ 2 5 ] ; Buffer : st r ing [ 2 5 5 ] ; S : Longint ; Sin , Sout : Text ; i : i n t e g e r ; begin S:= Socket ( AF UNIX, SOCK STREAM, 0 ) ; 271 13.2. FUNCTIONS AND PROCEDURES i f So cketE rr or <>0 then Perror ( ' C l i e n t : Socket : ' ) ; Saddr := ' ServerSoc ' ; i f not Connect ( S , SAddr , Sin , Sout ) then PError ( ' C l i e n t : Connect : ' ) ; Reset ( Sin ) ; ReWrite ( Sout ) ; Buffer := ' This i s a t e x t s t r i n g sent by the C l i e n t . ' ; for i :=1 to 10 do Writeln ( Sout , Buffer ) ; Flush ( Sout ) ; Readln ( SIn , Buffer ) ; WriteLn ( Buffer ) ; Close ( sout ) ; end . Connect Declaration: Function Connect (Sock:longint;const addr:string;var SockIn,SockOut:text) : Boolean; Description: This is an alternate form of the Connect (271) command. It is equivalent to subsequently calling the regular Connect (271) function and the Sock2Text (277) function. The function returns True if successfull, False otherwise. Errors: The errors are those of Connect (271). See also: Connect (271) Connect Declaration: Function Connect (Sock:longint;const addr:string;var SockIn,SockOut:file) : Boolean; Description: This is an alternate form of the Connect (271) command. The parameter addr contains the name of the unix socket file to be opened. It is equivalent to subse- quently calling the regular Connect (271) function and the Sock2File (276) function. The function returns True if successfull, False otherwise. Errors: The errors are those of Connect (271). See also: Connect (271) Connect Declaration: Function Connect (Sock:longint;const addr: TInetSockAddr;var SockIn,SockOut:file) : Boolean; Description: This is another alternate form of the Connect (271) command. It is equivalent to subsequently calling the regular Connect (271) function and the Sock2File (276) function. The Addr parameter contains the parameters of the internet socket to connect to. The function returns True if successfull, False otherwise. Errors: The errors are those of Connect (271). 272 13.2. FUNCTIONS AND PROCEDURES See also: Connect (271) program p f i n g e r ; uses s o c k e t s , e r r o r s ; Var Addr : TInetSockAddr ; S : Longint ; Sin , Sout : Text ; Line : strin g ; begin Addr . f a m i l y :=AF INET; { port 79 in network order } Addr . port :=79 shl 8 ; { l o c a l h o s t : 1 2 7 . 0 . 0 . 1 in network order } Addr . addr :=((1 shl 2 4 ) or 1 2 7 ) ; S:= Socket ( AF INET, SOCK STREAM, 0 ) ; I f Not Connect ( S ,ADDR, SIN , SOUT) Then begin Writeln ( ' Couldn ' ' t connect to l o c a l h o s t ' ) ; Writeln ( ' Socket e r r o r : ' , s t r e r r o r ( S ock et E rror ) ) ; halt ( 1 ) ; end ; rewrite ( sout ) ; reset ( sin ) ; writeln ( sout , paramstr ( 1 ) ) ; flush ( sout ) ; while not eof ( sin ) do begin readln ( Sin , l i n e ) ; writeln ( l i n e ) ; end ; c l o s e ( sin ) ; c l o s e ( sout ) ; end . GetPeerName Declaration: Function GetPeerName (Sock:Longint;Var Addr;Var Addrlen:Longint) : Longint; Description: GetPeerName returns the name of the entity connected to the specified socket Sock. The Socket must be connected for this call to work. Addr should point to enough space to store the name, the amount of space pointed to should be set in Addrlen. When the function returns succesfully, Addr will be filled with the name, and Addrlen will be set to the length of Addr. Errors: Errors are reported in SocketError, and include the following: SYS EBADFThe socket descriptor is invalid. SYS ENOBUFSThe system doesn't have enough bu ers to perform the opera- tion. SYS ENOTSOCKThe descriptor is not a socket. 273 13.2. FUNCTIONS AND PROCEDURES SYS EFAULTAddr points outside your address space. SYS ENOTCONNThe socket isn't connected. See also: Connect (271), Socket (277), connect (2) GetSocketName Declaration: Function GetSocketName (Sock:Longint;Var Addr;Var Addrlen:Longint) : Longint; Description: GetSockName returns the current name of the specified socket Sock. Addr should point to enough space to store the name, the amount of space pointed to should be set in Addrlen. When the function returns succesfully, Addr will be filled with the name, and Addrlen will be set to the length of Addr. Errors: Errors are reported in SocketError, and include the following: SYS EBADFThe socket descriptor is invalid. SYS ENOBUFSThe system doesn't have enough bu ers to perform the opera- tion. SYS ENOTSOCKThe descriptor is not a socket. SYS EFAULTAddr points outside your address space. See also: Bind (270) GetSocketOptions Declaration: Function GetSocketOptions (Sock,Level,OptName:Longint;Var OptVal;optlen:longint) : Longint; Description: GetSocketOptions gets the connection options for socket Sock. The socket may be obtained from di erent levels, indicated by Level, which can be one of the following: SOL SOCKETFrom the socket itself. XXXset Level to XXX, the protocol number of the protocol which should interprete the option. For more information on this call, refer to the unix manual page getsockopt (2) . Errors: Errors are reported in SocketError, and include the following: SYS EBADFThe socket descriptor is invalid. SYS ENOTSOCKThe descriptor is not a socket. SYS EFAULTOptVal points outside your address space. See also: GetSocketOptions (274) Listen Declaration: Function Listen (Sock,MaxConnect:Longint) : Boolean; Description: Listen listens for up to MaxConnect connections from socket Sock. The socket Sock must be of type SOCK STREAM or Sock SEQPACKET. The function returns True if a connection was accepted, False if an error occurred. 274 13.2. FUNCTIONS AND PROCEDURES Errors: Errors are reported in SocketError, and include the following: SYS EBADFThe socket descriptor is invalid. SYS ENOTSOCKThe descriptor is not a socket. SYS EOPNOTSUPPThe socket type doesn't support the Listen operation. See also: Socket (277), Bind (270), Connect (271) Recv Declaration: Function Recv (Sock:Longint;Var Addr;AddrLen,Flags:Longint) : Longint; Description: Recv reads at most Addrlen bytes from socket Sock into address Addr. The socket must be in a connected state. Flags can be one of the following: 1: Process out-of band data. 4: Bypass routing, use a direct interface. ??: Wait for full request or report an error. The functions returns the number of bytes actually read from the socket, or -1 if a detectable error occurred. Errors: Errors are reported in SocketError, and include the following: SYS EBADFThe socket descriptor is invalid. SYS ENOTCONNThe socket isn't connected. SYS ENOTSOCKThe descriptor is not a socket. SYS EFAULTThe address is outside your address space. SYS EMSGSIZEThe message cannot be sent atomically. SYS EWOULDBLOCKThe requested operation would block the process. SYS ENOBUFSThe system doesn't have enough free bu ers available. See also: Send (275) Send Declaration: Function Send (Sock:Longint;Var Addr;AddrLen,Flags:Longint) : Longint; Description: Send sends AddrLen bytes starting from address Addr to socket Sock. Sock must be in a connected state. The function returns the number of bytes sent, or -1 if a detectable error occurred. Flags can be one of the following: 1: Process out-of band data. 4: Bypass routing, use a direct interface. Errors: Errors are reported in SocketError, and include the following: SYS EBADFThe socket descriptor is invalid. SYS ENOTSOCKThe descriptor is not a socket. SYS EFAULTThe address is outside your address space. SYS EMSGSIZEThe message cannot be sent atomically. SYS EWOULDBLOCKThe requested operation would block the process. SYS ENOBUFSThe system doesn't have enough free bu ers available. See also: Recv (275), send (2) 275 13.2. FUNCTIONS AND PROCEDURES SetSocketOptions Declaration: Function SetSocketOptions (Sock,Level,OptName:Longint;Var OptVal;optlen:longint) : Longint; Description: SetSocketOptions sets the connection options for socket Sock. The socket may be manipulated at di erent levels, indicated by Level, which can be one of the following: SOL SOCKETTo manipulate the socket itself. XXXset Level to XXX, the protocol number of the protocol which should interprete the option. For more information on this call, refer to the unix manual page setsockopt (2) . Errors: Errors are reported in SocketError, and include the following: SYS EBADFThe socket descriptor is invalid. SYS ENOTSOCKThe descriptor is not a socket. SYS EFAULTOptVal points outside your address space. See also: GetSocketOptions (274) Shutdown Declaration: Function Shutdown (Sock:Longint;How:Longint) : Longint; Description: ShutDown closes one end of a full duplex socket connection, described by Sock. How determines how the connection will be shut down, and can be one of the following: 0: Further receives are disallowed. 1: Further sends are disallowed. 2: Sending nor receiving are allowed. On succes, the function returns 0, on error -1 is returned. Errors: SocketError is used to report errors, and includes the following: SYS EBADFThe socket descriptor is invalid. SYS ENOTCONNThe socket isn't connected. SYS ENOTSOCKThe descriptor is not a socket. See also: Socket (277), Connect (271) Sock2File Declaration: Procedure Sock2File (Sock:Longint;Var SockIn,SockOut:File); Description: Sock2File transforms a socket Sock into 2 Pascal file descriptors of type File, one for reading from the socket (SockIn), one for writing to the socket (SockOut). Errors: None. See also: Socket (277), Sock2Text (277) 276 13.2. FUNCTIONS AND PROCEDURES Sock2Text Declaration: Procedure Sock2Text (Sock:Longint;Var SockIn,SockOut: Text); Description: Sock2Text transforms a socket Sock into 2 Pascal file descriptors of type Text, one for reading from the socket (SockIn), one for writing to the socket (SockOut). Errors: None. See also: Socket (277), Sock2File (276) Socket Declaration: Function Socket (Domain,SocketType,Protocol:Longint) : Longint; Description: Socket creates a new socket in domain Domain, from type SocketType using pro- tocol Protocol. The Domain, Socket type and Protocol can be specified using predefined constants (see the section on constants for available constants) If succes- full, the function returns a socket descriptor, which can be passed to a subsequent Bind (270) call. If unsuccesfull, the function returns -1. Errors: Errors are returned in SocketError, and include the follwing: SYS EPROTONOSUPPORTThe protocol type or the specified protocol is not supported within this domain. SYS EMFILEThe per-process descriptor table is full. SYS ENFILEThe system file table is full. SYS EACCESSPermission to create a socket of the specified type and/or proto- col is denied. SYS ENOBUFSInsu cient bu er space is available. The socket cannot be cre- ated until su cient resources are freed. See also: SocketPair (277), socket (2) for an example, see Accept (268). SocketPair Declaration: Function SocketPair (Domain,SocketType,Protocol:Longint;var Pair:TSockArray) : Longint; Description: SocketPair creates 2 sockets in domain Domain, from type SocketType and using protocol Protocol. The pair is returned in Pair, and they are indistinguishable. The function returns -1 upon error and 0 upon success. Errors: Errors are reported in SocketError, and are the same as in Socket (277) See also: Str2UnixSockAddr (277) Str2UnixSockAddr Declaration: Procedure Str2UnixSockAddr(const addr:string;var t:TUnixSockAddr;var len:longint) Description: Str2UnixSockAddr transforms a Unix socket address in a string to a TUnixSockAddr structure which can be passed to the Bind (270) call. 277 13.2. FUNCTIONS AND PROCEDURES Errors: None. See also: Socket (277), Bind (270) 278 Chapter 14 The STRINGS unit. This chapter describes the STRINGS unit for Free Pascal. Since the unit only pro- vides some procedures and functions, there is only one section, which gives the declarations of these functions, together with an explanation. 14.1 Functions and procedures. StrAlloc Declaration: Function StrAlloc (Len : Longint);PChar Description: StrAlloc reserves memory on the heap for a string with length Len, terminating #0 included, and returns a pointer to it. Errors: If there is not enough memory, a run-time error occurs. See also: StrNew (286), StrPCopy (287). StrCat Declaration: Function StrCat (Dest,Source : PChar) : PChar; Description: Attaches Source to Dest and returns Dest. Errors: No length checking is performed. See also: Concat () Program Example11 ; Uses s t r i n g s ; { Program to demonstrate the StrCat f u n c t i o n . } Const P1 : PChar = ' This i s a PChar S t r i n g . ' ; Var P2 : PChar ; begin P2:= S t r A l l o c ( StrLen ( P1) 2+1); 279 14.1. FUNCTIONS AND PROCEDURES. StrMove ( P2 , P1 , StrLen ( P1 )+1); { P2=P1 } StrCat ( P2 , P1 ) ; { Append P2 once more } Writeln ( ' P2 : ' , P2 ) ; end . StrComp Declaration: Function StrComp (S1,S2 : PChar) : Longint; Description: Compares the null-terminated strings S1 and S2. The result is *A negative Longint when S1S2. Errors: None. See also: StrLComp (283), StrIComp (282), StrLIComp (285) For an example, see StrLComp (283). StrCopy Declaration: Function StrCopy (Dest,Source : PChar) : PChar; Description: Copy the null terminated string in Source to Dest, and returns a pointer to Dest. Dest needs enough room to contain Source, i.e. StrLen(Source)+1 bytes. Errors: No length checking is performed. See also: StrPCopy (287), StrLCopy (284), StrECopy (281) Program Example4 ; Uses s t r i n g s ; { Program to demonstrate the StrCopy f u n c t i o n . } Const P : PCHar = ' This i s a PCHAR s t r i n g . ' ; var PP : PChar ; begin PP:= S t r A l l o c ( Strlen (P)+1); STrCopy ( PP, P) ; I f StrComp ( PP, P)<>0 then Writeln ( ' Oh-oh problems . . . ' ) else Writeln ( ' A l l i s w e l l : PP=' , PP) ; end . 280 14.1. FUNCTIONS AND PROCEDURES. StrDispose Declaration: Procedure StrDispose (P : PChar); Description: Removes the string in P from the heap and releases the memory. Errors: None. See also: Dispose () , StrNew (286) Program Example17 ; Uses s t r i n g s ; { Program to demonstrate the St rD is po s e f u n c t i o n . } Const P1 : PChar = ' This i s a PChar s t r i n g ' ; var P2 : PChar ; begin Writeln ( ' Before StnNew : Memory a v a i l a b l e : ' , MemAvail ) ; P2:=StrNew ( P1 ) ; Writeln ( ' After StrNew : Memory a v a i l a b l e : ' , MemAvail ) ; Writeln ( ' P2 : ' , P2 ) ; StrDispose ( P2 ) ; Writeln ( ' After Str Di s pose : Memory a v a i l a b l e : ' , MemAvail ) ; end . StrECopy Declaration: Function StrECopy (Dest,Source : PChar) : PChar; Description: Copies the Null-terminated string in Source to Dest, and returns a pointer to the end (i.e. the terminating Null-character) of the copied string. Errors: No length checking is performed. See also: StrLCopy (284), StrCopy (280) Program Example6 ; Uses s t r i n g s ; { Program to demonstrate the StrECopy f u n c t i o n . } Const P : PChar = ' This i s a PCHAR s t r i n g . ' ; Var PP : PChar ; begin PP:= S t r A l l o c ( StrLen (P)+1); I f Longint ( StrECopy (PP, P))- Longint (PP)<>StrLen (P) then Writeln ( ' Something i s wrong here ! ' ) else Writeln ( ' PP= ' , PP) ; end . 281 14.1. FUNCTIONS AND PROCEDURES. StrEnd Declaration: Function StrEnd (P : PChar) : PChar; Description: Returns a pointer to the end of P. (i.e. to the terminating null-character. Errors: None. See also: StrLen (284) Program Example6 ; Uses s t r i n g s ; { Program to demonstrate the StrEnd f u n c t i o n . } Const P : PChar = ' This i s a PCHAR s t r i n g . ' ; begin I f Longint ( StrEnd (P))- Longint (P)<>StrLen (P) then Writeln ( ' Something i s wrong here ! ' ) else Writeln ( ' A l l i s w e l l . . ' ) ; end . StrIComp Declaration: Function StrIComp (S1,S2 : PChar) : Longint; Description: Compares the null-terminated strings S1 and S2, ignoring case. The result is *A negative Longint when S1S2. Errors: None. See also: StrLComp (283), StrComp (280), StrLIComp (285) Program Example8 ; Uses s t r i n g s ; { Program to demonstrate the StrLComp f u n c t i o n . } Const P1 : PChar = ' This i s the f i r s t s t r i n g . ' ; P2 : PCHar = ' This i s the second s t r i n g . ' ; Var L : Longint ; begin Write ( ' P1 and P2 are ' ) ; I f StrComp ( P1 , P2)<>0 then write ( ' NOT ' ) ; write ( ' equal . The f i r s t ' ) ; L :=1; 282 14.1. FUNCTIONS AND PROCEDURES. While StrLComp( P1 , P2 , L)=0 do inc ( L ) ; dec ( l ) ; Writeln ( l , ' c h a r a c t e r s are the same . ' ) ; end . StrLCat Declaration: Function StrLCat (Dest,Source : PChar; MaxLen : Longint) : PChar; Description: Adds MaxLen characters from Source to Dest, and adds a terminating null-character. Returns Dest. Errors: None. See also: StrCat (279) Program Example12 ; Uses s t r i n g s ; { Program to demonstrate the StrLCat f u n c t i o n . } Const P1 : PChar = '1234567890' ; Var P2 : PChar ; begin P2:= S t r A l l o c ( StrLen ( P1) 2+1); P2 :=#0; { Zero length } StrCat ( P2 , P1 ) ; StrLCat ( P2 , P1 , 5 ) ; Writeln ( ' P2 = ' , P2 ) ; end . StrLComp Declaration: Function StrLComp (S1,S2 : PChar; L : Longint) : Longint; Description: Compares maximum L characters of the null-terminated strings S1 and S2. The result is *A negative Longint when S1S2. Errors: None. See also: StrComp (280), StrIComp (282), StrLIComp (285) Program Example8 ; Uses s t r i n g s ; { Program to demonstrate the StrLComp f u n c t i o n . } 283 14.1. FUNCTIONS AND PROCEDURES. Const P1 : PChar = ' This i s the f i r s t s t r i n g . ' ; P2 : PCHar = ' This i s the second s t r i n g . ' ; Var L : Longint ; begin Write ( ' P1 and P2 are ' ) ; I f StrComp ( P1 , P2)<>0 then write ( ' NOT ' ) ; write ( ' equal . The f i r s t ' ) ; L :=1; While StrLComp( P1 , P2 , L)=0 do inc ( L ) ; dec ( l ) ; Writeln ( l , ' c h a r a c t e r s are the same . ' ) ; end . StrLCopy Declaration: Function StrLCopy (Dest,Source : PChar; MaxLen : Longint) : PChar; Description: Copies MaxLen characters from Source to Dest, and makes Dest a null terminated string. Errors: No length checking is performed. See also: StrCopy (280), StrECopy (281) Program Example5 ; Uses s t r i n g s ; { Program to demonstrate the StrLCopy f u n c t i o n . } Const P : PCHar = '123456789 ABCDEF' ; var PP : PCHar ; begin PP:= S t r A l l o c ( 1 1 ) ; Writeln ( ' F i r s t 10 c h a r a c t e r s of P : ' , StrLCopy ( PP, P , 1 0 ) ) ; end . StrLen Declaration: Function StrLen (p : PChar) : Longint; Description: Returns the length of the null-terminated string P. Errors: None. See also: Length () 284 14.1. FUNCTIONS AND PROCEDURES. Program Example1 ; Uses s t r i n g s ; { Program to demonstrate the StrLen f u n c t i o n . } Const P : PChar = ' This i s a constant pchar s t r i n g ' ; begin Writeln ( ' P : ' , p ) ; Writeln ( ' length (P ) : ' , StrLen (P) ) ; end . StrLIComp Declaration: Function StrLIComp (S1,S2 : PChar; L : Longint) : Longint; Description: Compares maximum L characters of the null-terminated strings S1 and S2, ignoring case. The result is *A negative Longint when S1S2. Errors: None. See also: StrLComp (283), StrComp (280), StrIComp (282) For an example, see StrIComp (282) StrLower Declaration: Function StrLower (P : PChar) : PChar; Description: Converts P to an all-lowercase string. Returns P. Errors: None. See also: Upcase () , StrUpper (289) Program Example14 ; Uses s t r i n g s ; { Program to demonstrate the StrLower and StrUpper f u n c t i o n s . } ConstP1 : PChar = 'THIS IS AN UPPERCASE PCHAR STRING' ; P2 : PChar = ' t h i s i s a lo w er ca s e s t r i n g ' ; begin Writeln ( ' Uppercase : ' , StrUpper ( P2 ) ) ; StrLower ( P1 ) ; Writeln ( ' Lowercase : ' , P1 ) ; end . 285 14.1. FUNCTIONS AND PROCEDURES. StrMove Declaration: Function StrMove (Dest,Source : PChar; MaxLen : Longint) : PChar; Description: Copies MaxLen characters from Source to Dest. No terminating null-character is copied. Returns Dest. Errors: None. See also: StrLCopy (284), StrCopy (280) Program Example10 ; Uses s t r i n g s ; { Program to demonstrate the StrMove f u n c t i o n . } Const P1 : PCHAR = ' This i s a pchar s t r i n g . ' ; Var P2 : Pchar ; begin P2:= S t r A l l o c ( StrLen ( P1)+1); StrMove ( P2 , P1 , StrLen ( P1 )+1); { P2:=P1 } Writeln ( ' P2 = ' , P2 ) ; end . StrNew Declaration: Function StrNew (P : PChar) : PChar; Description: Copies P to the Heap, and returns a pointer to the copy. Errors: Returns Nil if no memory was available for the copy. See also: New () , StrCopy (280), StrDispose (281) Program Example16 ; Uses s t r i n g s ; { Program to demonstrate the StrNew f u n c t i o n . } Const P1 : PChar = ' This i s a PChar s t r i n g ' ; var P2 : PChar ; begin P2:=StrNew ( P1 ) ; I f P1=P2 then writeln ( ' This can ' ' t be happening . . . ' ) else writeln ( ' P2 : ' , P2 ) ; end . 286 14.1. FUNCTIONS AND PROCEDURES. StrPas Declaration: Function StrPas (P : PChar) : String; Description: Converts a null terminated string in P to a Pascal string, and returns this string. The string is truncated at 255 characters. Errors: None. See also: StrPCopy (287) Program Example3 ; Uses s t r i n g s ; { Program to demonstrate the StrPas f u n c t i o n . } Const P : PChar = ' This i s a PCHAR s t r i n g ' ; var S : st r ing ; begin S:= StrPas ( P) ; Writeln ( ' S : ' , S ) ; end . StrPCopy Declaration: Function StrPCopy (Dest : PChar; Const Source : String) : PChar; Description: Converts the Pascal string in Source to a Null-terminated string, and copies it to Dest. Dest needs enough room to contain the string Source, i.e. Length(Source)+1 bytes. Errors: No length checking is performed. See also: StrPas (287) Program Example2 ; Uses s t r i n g s ; { Program to demonstrate the StrPCopy f u n c t i o n . } Const S = ' This i s a normal s t r i n g . ' ; Var P : Pchar ; begin p:= S t r A l l o c ( length ( S)+1); i f StrPCopy ( P, S)<>P then Writeln ( ' This i s i m p o s s i b l e ! ! ' ) else writeln ( P) ; end . 287 14.1. FUNCTIONS AND PROCEDURES. StrPos Declaration: Function StrPos (S1,S2 : PChar) : PChar; Description: Returns a pointer to the first occurrence of S2 in S1. If S2 does not occur in S1, returns Nil. Errors: None. See also: Pos () , StrScan (288), StrRScan (288) Program Example15 ; Uses s t r i n g s ; { Program to demonstrate the StrPos f u n c t i o n . } Const P : PChar = ' This i s a PChar s t r i n g . ' ; S : Pchar = ' i s ' ; begin Writeln ( ' P o s i t i o n of ' ' i s ' ' in P : ' , l o n g i n t ( StrPos (P, S))- Longint (P) ) ; end . StrRScan Declaration: Function StrRScan (P : PChar; C : Char) : PChar; Description: Returns a pointer to the last occurrence of the character C in the null-terminated string P. If C does not occur, returns Nil. Errors: None. See also: Pos () , StrScan (288), StrPos (288) For an example, see StrScan (288). StrScan Declaration: Function StrScan (P : PChar; C : Char) : PChar; Description: Returns a pointer to the first occurrence of the character C in the null-terminated string P. If C does not occur, returns Nil. Errors: None. See also: Pos () , StrRScan (288), StrPos (288) Program Example13 ; Uses s t r i n g s ; { Program to demonstrate the StrScan and StrRScan f u n c t i o n s . } Const P : PChar = ' This i s a PCHAR s t r i n g . ' ; S : Char = ' s ' ; 288 14.1. FUNCTIONS AND PROCEDURES. begin Writeln ( ' P, s t a r t i n g from f i r s t ' ' s ' ' : ' , StrScan (P, s ) ) ; Writeln ( ' P, s t a r t i n g from l a s t ' ' s ' ' : ' , StrRScan (P, s ) ) ; end . StrUpper Declaration: Function StrUpper (P : PChar) : PChar; Description: Converts P to an all-uppercase string. Returns P. Errors: None. See also: Upcase () , StrLower (285) For an example, see StrLower (285) 289 Chapter 15 The SYSUTILS unit. This chapter describes the sysutils unit. The sysutils unit was largely written by Gertjan Schouten, and completed by michael Van Canneyt. It aims to be compatible to the Delphi sysutils unit, but in contrast with the latter, it is designed to work on multiple platforms. This chapter starts out with a definition of all types and constants that are defined, followed by a complete explanation of each function. 15.1 Constants and types The following general-purpose constants are defined: const SecsPerDay = 24 * 60 * 60; // Seconds and milliseconds per day MSecsPerDay = SecsPerDay * 1000; DateDelta = 693594; // Days between 1/1/0001 and 12/31/1899 Eoln = #10; The following types are used frequently in date and time functions. They are the same on all platforms. typeTSystemTime = record Year, Month, Day: word; Hour, Minute, Second, MilliSecond: word; end ; TDateTime = double; TTimeStamp = record Time: integer; { Number of milliseconds since midnight } Date: integer; { One plus number of days since 1/1/0001 } end ; The following type is used in the FindFirst (322),FindNext (323) and FindClose (322) functions. The win32 version di ers from the other versions. If code is to be portable, that part shouldn't be used. 290 15.1. CONSTANTS AND TYPES Type THandle = Longint; TSearchRec = Record Time,Size, Attr : Longint; Name : TFileName; ExcludeAttr : Longint; FindHandle : THandle; {$ifdef Win32} FindData : TWin32FindData; {$endif} end; The following constants are file-attributes that need to be matched in the findfirst call. Const faReadOnly = $00000001; faHidden = $00000002; faSysFile = $00000004; faVolumeId = $00000008; faDirectory = $00000010; faArchive = $00000020; faAnyFile = $0000003f; The following constants can be used in the FileOpen (319) call. Const fmOpenRead = $0000; fmOpenWrite = $0001; fmOpenReadWrite = $0002; The following constants can be used in the FileSeek (320) call. Const fsFromBeginning = 0; fsFromCurrent = 1; fsFromEnd = 2; The following variables are used in the case translation routines. typeTCaseTranslationTable = array[0..255] of char; varUpperCaseTable: TCaseTranslationTable; LowerCaseTable: TCaseTranslationTable; The initialization code of the sysutils unit fills these tables with the appropriate values. For the win32 and go32v2 versions, this information is obtained from the operating system. The following constants control the formatting of dates. For the Win32 version of the sysutils unit, these constants are set according to the internationalization settings of Windows by the initialization code of the unit. 291 15.1. CONSTANTS AND TYPES Const DateSeparator: char = '-'; ShortDateFormat: string = 'd/m/y'; LongDateFormat: string = 'dd" "mmmm" "yyyy'; ShortMonthNames: array[1..12] of string[128] = ('Jan','Feb','Mar','Apr','May','Jun', 'Jul','Aug','Sep','Oct','Nov','Dec'); LongMonthNames: array[1..12] of string[128] = ('January','February','March','April', 'May','June','July','August', 'September','October','November','December'); ShortDayNames: array[1..7] of string[128] = ('Sun','Mon','Tue','Wed','Thu','Fri','Sat'); LongDayNames: array[1..7] of string[128] = ('Sunday','Monday','Tuesday','Wednesday', 'Thursday','Friday','Saturday'); The following constants control the formatting of times. For the Win32 version of the sysutils unit, these constants are set according to the internationalization settings of Windows by the initialization code of the unit. Const ShortTimeFormat: string = 'hh:nn'; LongTimeFormat: string = 'hh:nn:ss'; TimeSeparator: char = ':'; TimeAMString: string[7] = 'AM'; TimePMString: string[7] = 'PM'; The following constants control the formatting of currencies and numbers. For the Win32 version of the sysutils unit, these constants are set according to the internationalization settings of Windows by the initialization code of the unit. Const DecimalSeparator : Char = '.'; ThousandSeparator : Char = ','; CurrencyDecimals : Byte = 2; CurrencyString : String[7] = '$'; { Format to use when formatting currency : 0 = $1 1 = 1$ 2 = $ 1 3 = 1 $ 4 = Currency string replaces decimal indicator. e.g. 1$50 } CurrencyFormat : Byte = 1; { Same as above, only for negative currencies: 0 = ($1) 1 = -$1 2 = $-1 3 = $1- 4 = (1$) 5 = -1$ 6 = 1-$ 7 = 1$- 8 = -1 $ 9 = -$ 1 292 15.2. DATE AND TIME FUNCTIONS 10 = $ 1- } NegCurrFormat : Byte = 5; The following types are used in various string functions. typePString = ^String; TFloatFormat = (ffGeneral, ffExponent, ffFixed, ffNumber, ffCurrency); The following constants are used in the file name handling routines. Do not use a slash of backslash character directly as a path separator; instead use the OsDirSeparator character. Const DirSeparators : set of char = ['/','\']; {$ifdef Linux} OSDirSeparator = '/'; {$else} OsDirSeparator = '\'; {$endif} 15.2 Date and time functions Date and time formatting characters Various date and time formatting routines accept a format string. to format the date and or time. The following characters can be used to control the date and time formatting: c : shortdateformat + ' ' + shorttimeformat d : day of month dd : day of month (leading zero) ddd : day of week (abbreviation) dddd : day of week (full) ddddd : shortdateformat dddddd : longdateformat m : month mm : month (leading zero) mmm : month (abbreviation) mmmm : month (full) y : year (four digits) yy : year (two digits) yyyy : year (with century) 293 15.2. DATE AND TIME FUNCTIONS h : hour hh : hour (leading zero) n : minute nn : minute (leading zero) s : second ss : second (leading zero) t : shorttimeformat tt : longtimeformat am/pm : use 12 hour clock and display am and pm accordingly a/p : use 12 hour clock and display a and p accordingly / : insert date seperator : : insert time seperator "xx" : literal text 'xx' : literal text TDateTime Declaration: TDateTime = Double; Description: Many functions return or require a TDateTime type, which contains a date and time in encoded form. The date and time are converted to a double as follows: Date Declaration: Function Date: TDateTime; Description: Date returns the current date in TDateTime format. For more information about the TDateTime type, see TDateTime (294). Errors: None. See also: Time (306),Now (303), TDateTime (294). Program Example1 ; { This program demonstrates the Date f u n c t i o n } uses s y s u t i l s ; Var YY,MM, DD : Word ; Begin Writeln ( ' Date : ' , Date ) ; DeCodeDate ( Date , YY,MM, DD) ; Writeln ( format ( ' Date i s (DD/MM/YY): % d/%d/%d ' , [ dd ,mm, yy ] ) ) ; End. 294 15.2. DATE AND TIME FUNCTIONS DateTimeToFileDate Declaration: Function DateTimeToFileDate(DateTime : TDateTime) : Longint; Description: DateTimeToFileDate function converts a date/time indication in TDateTime for- mat to a filedate function, such as returned for instance by the FileAge (315) func- tion. Errors: None. See also: Time (306), Date (294), FileDateToDateTime (300), DateTimeToSystemTime (296), DateTimeToTimeStamp (297) Program Example2 ; { This program demonstrates the DateTimeToFileDate f u n c t i o n } Uses s y s u t i l s ; Begin Writeln ( ' FileTime of now would be : ' , DateTimeToFileDate ( Now) ) ; End. DateTimeToStr Declaration: Function DateTimeToStr(DateTime: TDateTime): string; Description: DateTimeToStr returns a string representation of DateTime using the formatting specified in ShortDateTimeFormat. It corresponds to a call to FormatDateTime('c',DateTime) (see section 15.2, page 293). Errors: None. See also: FormatDateTime (301), TDateTime (294). Program Example3 ; { This program demonstrates the DateTimeToStr f u n c t i o n } Uses s y s u t i l s ; Begin Writeln ( ' Today i s : ' , DateTimeToStr (Now) ) ; Writeln ( ' Today i s : ' , FormatDateTime ( ' c ' , Now) ) ; End. DateTimeToString Declaration: Procedure DateTimeToString(var Result: string; const FormatStr: string; const DateTime: TDateTime); Description: DateTimeToString returns in Result a string representation of DateTime using the formatting specified in FormatStr. for a list of characters that can be used in the FormatStr formatting string, see section 15.2, page 293. 295 15.2. DATE AND TIME FUNCTIONS Errors: In case a wrong formatting character is found, an EConvertError is raised. See also: FormatDateTime (301), section 15.2, page 293. Program Example4 ; { This program demonstrates the DateTimeToString f u n c t i o n } Uses s y s u t i l s ; Procedure today ( Fmt : s tr in g ) ; Var S : A n s i S t r i n g ; begin DateTimeToString ( S , Fmt , Date ) ; Writeln ( S ) ; end ; Procedure Now ( Fmt : st r ing ) ; Var S : A n s i S t r i n g ; begin DateTimeToString ( S , Fmt , Time ) ; Writeln ( S ) ; end ; Begin Today ( '" Today i s " dddd dd mmmm y ' ) ; Today ( '" Today i s " d mmm yy ' ) ; Today ( '" Today i s " d/mmm/ yy ' ) ; Now ( ' ' ' The time i s ' ' am/pmh: n : s ' ) ; Now ( ' ' ' The time i s ' ' hh : nn : ssam /pm' ) ; Now ( ' ' ' The time i s ' ' tt ' ) ; End. DateTimeToSystemTime Declaration: Procedure DateTimeToSystemTime(DateTime: TDateTime; var SystemTime: TSystemTime); Description: DateTimeToSystemTime converts a date/time pair in DateTime, with TDateTime format to a system time SystemTime. Errors: None. See also: DateTimeToFileDate (295), SystemTimeToDateTime (305), DateTimeToTimeStamp (297) Program Example5 ; { This program demonstrates the DateTimeToSystemTime f u n c t i o n } 296 15.2. DATE AND TIME FUNCTIONS Uses s y s u t i l s ; Var ST : TSystemTime ; Begin DateTimeToSystemTime (Now, ST) ; With St do begin Writeln ( ' Today i s ' , year , ' / ' , month , ' / ' , Day ) ; Writeln ( ' The time i s ' , Hour , ' : ' , minute , ' : ' , Second , ' . ' , M i l l i S e c o n d ) ; end ; End. DateTimeToTimeStamp Declaration: Function DateTimeToTimeStamp(DateTime: TDateTime): TTimeStamp; Description: DateTimeToSystemTime converts a date/time pair in DateTime, with TDateTime format to a TTimeStamp format. Errors: None. See also: DateTimeToFileDate (295), SystemTimeToDateTime (305), DateTimeToSystemTime (296) Program Example6 ; { This program demonstrates the DateTimeToTimeStamp f u n c t i o n } Uses s y s u t i l s ; Var TS : TTimeStamp ; Begin TS:=DateTimeToTimeStamp ( Now) ; With TS do begin Writeln ( ' Now i s ' , time , ' m i l l i s e c o n d past midnight ' ) ; Writeln ( ' Today i s ' , Date , ' days past 1/1/0001' ) ; end ; End. DateToStr Declaration: Function DateToStr(Date: TDateTime): string; Description: DateToStr converts Date to a string representation. It uses ShortDateFormat as it's formatting string. It is hence completely equivalent to a FormatDateTime('ddddd', Date). Errors: None. See also: TimeToStr (307), DateTimeToStr (295), FormatDateTime (301), StrToDate (303) 297 15.2. DATE AND TIME FUNCTIONS Program Example7 ; { This program demonstrates the DateToStr f u n c t i o n } Uses s y s u t i l s ; Begin Writeln ( Format ( ' Today i s : % s ' , [ DateToStr ( Date ) ] ) ) ; End. DayOfWeek Declaration: Function DayOfWeek(DateTime: TDateTime): integer; Description: DayOfWeek returns the day of the week from DateTime. Sunday is counted as day 1, Saturday is counted as day 7. The result of DayOfWeek can serve as an index to the LongDayNames constant array, to retrieve the name of the day. Errors: None. See also: Date (294), DateToStr (297) Program Example8 ; { This program demonstrates the DayOfWeek f u n c t i o n } Uses s y s u t i l s ; Begin Writeln ( ' Today ' ' s day i s ' , LongDayNames [ DayOfWeek( Date ) ] ) ; End. DecodeDate Declaration: Procedure DecodeDate(Date: TDateTime; var Year, Month, Day: word); Description: DecodeDate decodes the Year, Month and Day stored in Date, and returns them in the Year, Month and Day variables. Errors: None. See also: EncodeDate (299), DecodeTime (299). Program Example9 ; { This program demonstrates the DecodeDate f u n c t i o n } Uses s y s u t i l s ; Var YY,MM, DD : Word ; Begin DecodeDate ( Date , YY,MM, DD) ; Writeln ( Format ( ' Today i s %d/%d/%d ' , [ dd ,mm, yy ] ) ) ; End. 298 15.2. DATE AND TIME FUNCTIONS DecodeTime Declaration: Procedure DecodeTime(Time: TDateTime; var Hour, Minute, Second, MilliSecond: word); Description: DecodeDate decodes the hours, minutes, second and milliseconds stored in Time, and returns them in the Hour, Minute and Second and MilliSecond variables. Errors: None. See also: EncodeTime (300), DecodeDate (298). Program Example10 ; { This program demonstrates the DecodeTime f u n c t i o n } Uses s y s u t i l s ; Var HH,MM, SS , MS: Word ; Begin DecodeTime( Time, HH,MM, SS , MS) ; Writeln ( format ( ' The time i s %d:%d:%d.%d ' , [ hh ,mm, ss , ms ] ) ) ; End. EncodeDate Declaration: Function EncodeDate(Year, Month, Day :word): TDateTime; Description: EncodeDate encodes the Year, Month and Day variables to a date in TDateTime format. It does the opposite of the DecodeDate (298) procedure. The parameters must lie withing valid ranges (boundaries included): Yearmust be between 1 and 9999. Monthmust be within the range 1-12. Daymsut be between 1 and 31. Errors: In case one of the parameters is out of it's valid range, 0 is returned. See also: EncodeTime (300), DecodeDate (298). Program Example11 ; { This program demonstrates the EncodeDate f u n c t i o n } Uses s y s u t i l s ; Var YY,MM, DD : Word ; Begin DecodeDate ( Date , YY,MM, DD) ; WriteLn ( ' Today i s : ' , FormatDateTime ( ' dd mmmm yyyy ' , EnCodeDate(YY,Mm, Dd ) ) ) ; End. 299 15.2. DATE AND TIME FUNCTIONS EncodeTime Declaration: Function EncodeTime(Hour, Minute, Second, MilliSecond:word): TDateTime; Description: EncodeTime encodes the Hour, Minute, Second, MilliSecond variables to a TDateTime format result. It does the opposite of the DecodeTime (299) procedure. The parameters must have a valid range (boundaries included): Hourmust be between 0 and 23. Minute,secondmust both be between 0 and 59. Millisecondmust be between 0 and 999. Errors: In case one of the parameters is outside of it's valid range, 0 is returned. See also: EncodeDate (299), DecodeTime (299). Program Example12 ; { This program demonstrates the EncodeTime f u n c t i o n } Uses s y s u t i l s ; Var Hh,MM, SS , MS : Word ; Begin DeCodeTime ( Time, Hh,MM, SS , MS) ; Writeln ( ' Present Time i s : ' , FormatDateTime ( ' hh :mm: ss ' , EnCodeTime ( HH,MM, SS , MS) ) ) ; End. FileDateToDateTime Declaration: Function FileDateToDateTime(Filedate : Longint) : TDateTime; Description: FileDateToDateTime converts the date/time encoded in filedate to a TDateTime encoded form. It can be used to convert date/time values returned by the FileAge (315) or FindFirst (322)/FindNext (323) functions to TDateTime form. Errors: None. See also: DateTimeToFileDate (295) Program Example13 ; { This program demonstrates the FileDateToDateTime f u n c t i o n } Uses s y s u t i l s ; VarThisAge : Longint ; Begin Write ( ' ex13 . pp cr eated on : ' ) ; ThisAge := FileAge ( ' ex13 . pp ' ) ; Writeln ( DateTimeToStr ( FileDateToDateTime ( ThisAge ) ) ) ; End. 300 15.2. DATE AND TIME FUNCTIONS FormatDateTime Declaration: Function FormatDateTime(FormatStr: string; DateTime: TDateTime):string; Description: FormatDateTime formats the date and time encoded in DateTime according to the formatting given in FormatStr. The complete list of formatting characters can be found in section 15.2, page 293. Errors: On error (such as an invalid character in the formatting string), and EConvertError exception is raised. See also: DateTimeToStr (295), DateToStr (297), TimeToStr (307), StrToDateTime (304) Program Example14 ; { This program demonstrates the FormatDateTime f u n c t i o n } Uses s y s u t i l s ; Var ThisMoment : TDateTime ; Begin ThisMoment :=Now; Writeln ( ' Now : ' , FormatDateTime ( ' hh :mm' , ThisMoment ) ) ; Writeln ( ' Now : ' , FormatDateTime ( ' DD MM YYYY' , ThisMoment ) ) ; Writeln ( ' Now : ' , FormatDateTime ( ' c ' , ThisMoment ) ) ; End. IncMonth Declaration: Function IncMonth(const DateTime: TDateTime; NumberOfMonths: integer): TDateTime; Description: IncMonth increases the month number in DateTime with NumberOfMonths. It wraps the result as to get a month between 1 and 12, and updates the year ac- cordingly. NumberOfMonths can be negative, and can be larger than 12 (in absolute value). Errors: None. See also: Date (294), Time (306), Now (303) Program Example15 ; { This program demonstrates the IncMonth f u n c t i o n } Uses s y s u t i l s ; Var ThisDay : TDateTime ; Begin ThisDay :=Date ; Writeln ( ' ThisDay : ' , DateToStr ( ThisDay ) ) ; Writeln ( '6 months ago : ' , DateToStr ( IncMonth ( ThisDay , - 6 ) ) ) ; Writeln ( '6 months from now : ' , DateToStr ( IncMonth ( ThisDay , 6 ) ) ) ; Writeln ( '12 months ago : ' , DateToStr ( IncMonth ( ThisDay , -12 ) ) ) ; 301 15.2. DATE AND TIME FUNCTIONS Writeln ( '12 months from now : ' , DateToStr ( IncMonth ( ThisDay , 1 2 ) ) ) ; Writeln ( '18 months ago : ' , DateToStr ( IncMonth ( ThisDay , -1 8) ) ) ; Writeln ( '18 months from now : ' , DateToStr ( IncMonth ( ThisDay , 1 8 ) ) ) ; End. IsLeapYear Declaration: Function IsLeapYear(Year: Word): boolean; Description: IsLeapYear returns True if Year is a leap year, False otherwise. Errors: None. See also: IncMonth (301), Date (294) Program Example16 ; { This program demonstrates the IsLeapYear f u n c t i o n } Uses s y s u t i l s ; Var YY,MM, dd : Word ; Procedure TestYear ( Y : Word ) ; begin Writeln ( Y, ' i s leap year : ' , IsLeapYear (Y) ) ; end ; Begin DeCodeDate( Date , YY,mm, dd ) ; TestYear ( yy ) ; TestYear (2000); TestYear (1900); TestYear (1600); TestYear (1992); TestYear (1995); End. MSecsToTimeStamp Declaration: Function MSecsToTimeStamp(MSecs: Comp): TTimeStamp; Description: MSecsTiTimeStamp converts the given number of milliseconds to a TTimeStamp date/time notation. Use TTimeStamp variables if you need to keep very precise track of time. Errors: None. See also: TimeStampToMSecs (307), DateTimeToTimeStamp (297), Program Example17 ; { This program demonstrates the MSecsToTimeStamp f u n c t i o n } 302 15.2. DATE AND TIME FUNCTIONS Uses s y s u t i l s ; Var MS : Comp; TS : TTimeStamp ; DT : TDateTime ; Begin TS:=DateTimeToTimeStamp (Now) ; Writeln ( ' Now in days s i n c e 1 / 1 / 0 0 0 1 : ' , TS. Date ) ; Writeln ( ' Now in m i l l i s e c s s i n c e midnight : ' , TS. Time ) ; MS:=TimeStampToMSecs ( TS) ; Writeln ( ' Now in m i l l i s e c s s i n c e 1/1/0001 : ' , MS) ; MS:=MS-1000 3600 2; TS:=MSecsToTimeStamp (MS) ; DT:=TimeStampToDateTime ( TS) ; Writeln ( ' Now minus 1 day : ' , DateTimeToStr (DT) ) ; End. Now Declaration: Function Now: TDateTime; Description: Now returns the current date and time. It is equivalent to Date+Time. Errors: None. See also: Date (294), Time (306) Program Example18 ; { This program demonstrates the Now f u n c t i o n } Uses s y s u t i l s ; Begin Writeln ( ' Now : ' , DateTimeToStr (Now) ) ; End. StrToDate Declaration: Function StrToDate(const S: string): TDateTime; Description: StrToDate converts the string S to a TDateTime date value. The Date must consist of 1 to three digits, separated by the DateSeparator character. If two numbers are given, they are supposed to form the day and month of the current year. If only one number is given, it is supposed to represent the day of the current month. (This is not supported in Delphi) The order of the digits (y/m/d, m/d/y, d/m/y) is determined from the ShortDateFormat variable. Errors: On error (e.g. an invalid date or invalid character), an EConvertError exception is raised. See also: StrToTime (305), DateToStr (297)n TimeToStr (307). 303 15.2. DATE AND TIME FUNCTIONS Program Example19 ; { This program demonstrates the StrToDate f u n c t i o n } Uses s y s u t i l s ; Procedure TestStr ( S : String ) ; begin Writeln ( S , ' : ' , DateToStr ( StrToDate ( S ) ) ) ; end ; Begin Writeln ( ' ShortDateFormat ' , ShortDateFormat ) ; TestStr ( DateTimeToStr ( Date ) ) ; TestStr ( '05/05/1999' ) ; TestStr ( ' 5 / 5 ' ) ; TestStr ( ' 5 ' ) ; End. StrToDateTime Declaration: Function StrToDateTime(const S: string): TDateTime; Description: StrToDateTime converts the string S to a TDateTime date and time value. The Date must consist of 1 to three digits, separated by the DateSeparator character. If two numbers are given, they are supposed to form the day and month of the current year. If only one number is given, it is supposed to represent the day of the current month. (This is not supported in Delphi) The order of the digits (y/m/d, m/d/y, d/m/y) is determined from the ShortDateFormat variable. Errors: On error (e.g. an invalid date or invalid character), an EConvertError exception is raised. See also: StrToDate (303), StrToTime (305), DateTimeToStr (295) Program Example20 ; { This program demonstrates the StrToDateTime f u n c t i o n } Uses s y s u t i l s ; Procedure TestStr ( S : String ) ; begin Writeln ( S , ' : ' , DateTimeToStr ( StrToDateTime ( S ) ) ) ; end ; Begin Writeln ( ' ShortDateFormat ' , ShortDateFormat ) ; TestStr ( DateTimeToStr (Now) ) ; 304 15.2. DATE AND TIME FUNCTIONS TestStr ( '05-05-1999 15:50' ) ; TestStr ( '5-5 13:30' ) ; TestStr ( ' 5 1 : 3 0 PM' ) ; End. StrToTime Declaration: Function StrToTime(const S: string): TDateTime; Description: StrToTime converts the string S to a TDateTime time value. The time must consist of 1 to 4 digits, separated by the TimeSeparator character. If two numbers are given, they are supposed to form the hour and minutes. Errors: On error (e.g. an invalid date or invalid character), an EConvertError exception is raised. See also: StrToDate (303), StrToDateTime (304), TimeToStr (307) Program Example21 ; { This program demonstrates the StrToTime f u n c t i o n } Uses s y s u t i l s ; Procedure TestStr ( S : String ) ; begin Writeln ( S , ' : ' , TimeToStr ( StrToTime ( S ) ) ) ; end ; Begin t e s t s t r ( TimeToStr ( Time ) ) ; t e s t s t r ( ' 1 2 : 0 0 ' ) ; t e s t s t r ( ' 1 5 : 3 0 ' ) ; t e s t s t r ( ' 3 : 3 0 PM' ) ; End. SystemTimeToDateTime Declaration: Function SystemTimeToDateTime(const SystemTime: TSystemTime): TDateTime; Description: SystemTimeToDateTime converts a TSystemTime record to a TDateTime style date/time indication. Errors: None. See also: DateTimeToSystemTime (296) Program Example22 ; { This program demonstrates the SystemTimeToDateTime f u n c t i o n } Uses s y s u t i l s ; 305 15.2. DATE AND TIME FUNCTIONS Var ST : TSystemTime ; Begin DateTimeToSystemTime (Now, ST) ; With St do begin Writeln ( ' Today i s ' , year , ' / ' , month , ' / ' , Day ) ; Writeln ( ' The time i s ' , Hour , ' : ' , minute , ' : ' , Second , ' . ' , M i l l i S e c o n d ) ; end ; Writeln ( ' Converted : ' , DateTimeToStr ( SystemTimeToDateTime ( ST ) ) ) ; End. Time Declaration: Function Time: TDateTime; Description: Time returns the current time in TDateTime format. The date part of the TDateTimeValue is set to zero. Errors: None. See also: Now (303), Date (294) Program Example23 ; { This program demonstrates the Time f u n c t i o n } Uses s y s u t i l s ; Begin Writeln ( ' The time i s : ' , TimeToStr ( Time ) ) ; End. TimeStampToDateTime Declaration: Function TimeStampToDateTime(const TimeStamp: TTimeStamp): TDateTime; Description: TimeStampToDateTime converts TimeStamp to a TDateTime format variable. It is the inverse operation of DateTimeToTimeStamp (297). Errors: None. See also: DateTimeToTimeStamp (297), TimeStampToMSecs (307) Program Example24 ; { This program demonstrates the TimeStampToDateTime f u n c t i o n } Uses s y s u t i l s ; Var TS : TTimeStamp ; DT : TDateTime ; Begin 306 15.3. DISK FUNCTIONS TS:=DateTimeToTimeStamp ( Now) ; With TS do begin Writeln ( ' Now i s ' , time , ' m i l l i s e c o n d past midnight ' ) ; Writeln ( ' Today i s ' , Date , ' days past 1/1/0001' ) ; end ; DT:=TimeStampToDateTime ( TS) ; Writeln ( ' Together t h i s i s : ' , DateTimeToStr (DT) ) ; End. TimeStampToMSecs Declaration: Function TimeStampToMSecs(const TimeStamp: TTimeStamp): comp; Description: TimeStampToMSecs converts TimeStamp to the number of seconds since 1/1/0001. Use TTimeStamp variables if you need to keep very precise track of time. Errors: None. See also: MSecsToTimeStamp (302), TimeStampToDateTime (306) For an example, see MSecsToTimeStamp (302). TimeToStr Declaration: Function TimeToStr(Time: TDateTime): string; Description: TimeToStr converts the time in Time to a string. It uses the ShortTimeFormat variable to see what formatting needs to be applied. It is therefor entirely equivalent to a FormatDateTime('t',Time) call. Errors: None. See also: Program Example25 ; { This program demonstrates the TimeToStr f u n c t i o n } Uses s y s u t i l s ; Begin Writeln ( ' The c u r r e n t time i s : ' , TimeToStr ( Time ) ) ; End. 15.3 Disk functions AddDisk (Linux only) Declaration: Function AddDisk (Const PAth : String) : Longint; Description: On Linux both the DiskFree (36) and DiskSize (37) functions need a file on the specified drive, since is required for the statfs system call. These filenames are set in drivestr[0..26], and the first 4 have been preset to : 307 15.3. DISK FUNCTIONS Disk 0'.' default drive - hence current directory is used. Disk 1'/fd0/.' floppy drive 1. Disk 2'/fd1/.' floppy drive 2. Disk 3'/' C: equivalent of DOS is the root partition. Drives 4..26 can be set by your own applications with the AddDisk call. The AddDisk call adds Path to the names of drive files, and returns the number of the disk that corresponds to this drive. If you add more than 21 drives, the count is wrapped to 4. Errors: None. See also: DiskFree (308), DiskSize (309) CreateDir Declaration: Function CreateDir(Const NewDir : String) : Boolean; Description: CreateDir creates a new directory with name NewDir. If the directory doesn't contain an absolute path, then the directory is created below the current working directory. The function returns True if the directory was successfully created, False otherwise. Errors: In case of an error, the function returns False. See also: RemoveDir (310) Program Example26 ; { This program demonstrates the CreateDir and RemoveDir f u n c t i o n s } { Run t h i s program twice in the same d i r e c t o r y } Uses s y s u t i l s ; Begin I f Not F i l e E x i s t s ( ' NewDir ' ) then I f Not CreateDir ( ' NewDir ' ) Then Writeln ( ' F a i l e d to c r e a t e d i r e c t o r y ! ' ) else Writeln ( ' Created " NewDir " d i r e c t o r y ' ) Else I f Not RemoveDir ( ' NewDir ' ) Then Writeln ( ' F a i l e d to remove d i r e c t o r y ! ' ) else Writeln ( ' Removed " NewDir " d i r e c t o r y ' ) ; End. DiskFree Declaration: Function DiskFree(Drive : Byte) : Longint; Description: DiskFree returns the free space (in bytes) on disk Drive. Drive is the number of the disk drive: 308 15.3. DISK FUNCTIONS 0for the current drive. 1for the first floppy drive. 2for the second floppy drive. 3for the first hard-disk parttion. 4-26for all other drives and partitions. Remark Under linux, and Unix in general, the concept of disk is di erent than the dos one, since the filesystem is seen as one big directory tree. For this reason, the DiskFree and DiskSize (37) functions must be mimicked using filenames that reside on the partitions. For more information, see AddDisk (307) Errors: On error, -1 is returned. See also: DiskSize (309), AddDisk (307) Program Example27 ; { This program demonstrates the DiskFree f u n c t i o n } Uses s y s u t i l s ; Begin Write ( ' Size of c u r r e n t disk : ' , DiskSize ( 0 ) ) ; Writeln ( ' (= ' , DiskSize ( 0 ) div 1024, ' k ) ' ) ; Write ( ' Free space of c u r r e n t disk : ' , Diskfree ( 0 ) ) ; Writeln ( ' (= ' , Diskfree ( 0 ) div 1024, ' k ) ' ) ; End. DiskSize Declaration: Function DiskSize(Drive : Byte) : Longint; Description: DiskSize returns the size (in bytes) of disk Drive. Drive is the number of the disk drive: 0for the current drive. 1for the first floppy drive. 2for the second floppy drive. 3for the first hard-disk parttion. 4-26for all other drives and partitions. Remark Under linux, and Unix in general, the concept of disk is di erent than the dos one, since the filesystem is seen as one big directory tree. For this reason, the DiskFree (36) and DiskSize functions must be mimicked using filenames that reside on the partitions. For more information, see AddDisk (307) Errors: On error, -1 is returned. See also: DiskFree (308), AddDisk (307) For an example, see DiskFree (308). 309 15.3. DISK FUNCTIONS GetCurrentDir Declaration: Function GetCurrentDir : String; Description: GetCurrentDir returns the current working directory. Errors: None. See also: SetCurrentDir (310), DiskFree (36), DiskSize (37) Program Example28 ; { This program demonstrates the GetCurrentDir f u n c t i o n } Uses s y s u t i l s ; Begin Writeln ( ' Current D i r e c t o r y i s : ' , GetCurrentDir ) ; End. RemoveDir Declaration: Function RemoveDir(Const Dir : String) : Boolean; Description: RemoveDir removes directory Dir from the disk. If the directory is not absolue, it is appended to the current working directory. Errors: In case of error (e.g. the directory isn't empty) the function returns False. If successful, True is returned. See also: For an example, see CreateDir (308). SetCurrentDir Declaration: Function SetCurrentDir(Const NewDir : String) : Boolean; Description: SetCurrentDir sets the current working directory of your program to NewDir. It returns True if the function was successfull, False otherwise. Errors: In case of error, False is returned. See also: GetCurrentDir (310) Program Example29 ; { This program demonstrates the S e t C u r r e n t D i r f u n c t i o n } Uses s y s u t i l s ; Begin I f S e t C u r r e n t D i r ( ' . . ' ) Then Writeln ( ' Now in d i r e c t o r y ' , GetCurrentDir ) else Writeln ( ' Change d i r e c t o r y to . . f a i l e d . ' ) ; End. 310 15.4. FILE HANDLING FUNCTIONS 15.4 File handling functions ChangeFileExt Declaration: Function ChangeFileExt(const FileName, Extension: string): string; Description: ChangeFileExt changes the file extension in FileName to Extension. The exten- sion Extension includes the starting . (dot). The previous extension of FileName are all characters after the last ., the . character included. If FileName doesn't have an extension, Extension is just appended. Errors: None. See also: ExtractFileName (314), ExtractFilePath (314), ExpandFileName (312) DeleteFile Declaration: Function DeleteFile(Const FileName : String) : Boolean; Description: DeleteFile deletes file FileName from disk. The function returns True if the file was successfully removed, False otherwise. Errors: On error, False is returned. See also: FileCreate (316), FileExists (317) Program Example31 ; { This program demonstrates the D e l e t e F i l e f u n c t i o n } Uses s y s u t i l s ; VarLine : String ; F, I : Longint ; Begin F:= F i l e C r e a t e ( ' t e s t . txt ' ) ; Line := ' Some s t r i n g l i n e . ' #10; For I :=1 to 10 do F i l e W r i t e ( F, Line [ 1 ] , Length ( Line ) ) ; FileClose ( F ) ; DeleteFile ( ' t e s t . txt ' ) ; End. DoDirSeparators Declaration: Procedure DoDirSeparators(Var FileName : String); Description: This function replaces all directory separators '´and '/' to the directory separator character for the current system. Errors: None. See also: ExtractFileName (314), ExtractFilePath (314) 311 15.4. FILE HANDLING FUNCTIONS Program Example32 ; { This program demonstrates the DoDirSeparators f u n c t i o n } {$H+} Uses s y s u t i l s ; Procedure T e s t i t ( F : String ) ; begin Writeln ( ' Before : ' , F ) ; DoDirSeparators ( F ) ; Writeln ( ' After : ' , F ) ; end ; Begin T e s t i t ( GetCurrentDir ) ; T e s t i t ( ' c :\ pp\ bin \ win32 ' ) ; T e s t i t ( '/ usr / l i b / fpc ' ) ; T e s t i t ( '\ usr \ l i b \ fpc ' ) ; End. ExpandFileName Declaration: Function ExpandFileName(Const FileName : string): String; Description: ExpandFileName expands the filename to an absolute filename. It changes all directory separator characters to the one appropriate for the system first. Errors: None. See also: ExtractFileName (314), ExtractFilePath (314), ExtractFileDir (313), ExtractFileDrive (313), ExtractFileExt (314), ExtractRelativePath (315) Program Example33 ; { This program demonstrates the ExpandFileName f u n c t i o n } Uses s y s u t i l s ; Procedure T e s t i t ( F : String ) ; begin Writeln ( F, ' expands to : ' , ExpandFileName ( F ) ) ; end ; Begin T e s t i t ( ' ex33 . pp ' ) ; T e s t i t ( ParamStr ( 0 ) ) ; T e s t i t ( '/ pp/ bin / win32 / ppc386 ' ) ; T e s t i t ( '\ pp\ bin \ win32 \ ppc386 ' ) ; T e s t i t ( ' . ' ) ; End. 312 15.4. FILE HANDLING FUNCTIONS ExpandUNCFileName Declaration: Function ExpandUNCFileName(Const FileName : string): String; Description: ExpandUNCFileName runs ExpandFileName (312) on FileName and then attempts to replace the driveletter by the name of a shared disk. Errors: See also: ExtractFileName (314), ExtractFilePath (314), ExtractFileDir (313), ExtractFileDrive (313), ExtractFileExt (314), ExtractRelativePath (315) ExtractFileDir Declaration: Function ExtractFileDir(Const FileName : string): string; Description: ExtractFileDir returns only the directory part of FileName, not including a driveletter. The directory name has NO ending directory separator, in di erence with ExtractFilePath (314). Errors: None. See also: ExtractFileName (314), ExtractFilePath (314), ExtractFileDir (313), ExtractFileDrive (313), ExtractFileExt (314), ExtractRelativePath (315) Program Example34 ; { This program demonstrates the ExtractFileName f u n c t i o n } {$H+} Uses s y s u t i l s ; Procedure T e s t i t ( F : String ) ; begin Writeln ( ' FileName : ' , F ) ; Writeln ( ' Has Name : ' , ExtractFileName ( F ) ) ; Writeln ( ' Has Path : ' , ExtractFilePath ( F ) ) ; Writeln ( ' Has Extension : ' , ExtractFileExt ( F ) ) ; Writeln ( ' Has D i r e c t o r y : ' , E x t r a c t F i l e D i r ( F ) ) ; Writeln ( ' Has Drive : ' , E x t r a c t F i l e D r i v e ( F ) ) ; end ; Begin T e s t i t ( Paramstr ( 0 ) ) ; T e s t i t ( '/ usr / l o c a l / bin / mysqld ' ) ; T e s t i t ( ' c :\ pp\ bin \ win32 \ ppc386 . exe ' ) ; T e s t i t ( '/ pp/ bin / win32 / ppc386 . exe ' ) ; End. ExtractFileDrive Declaration: Function ExtractFileDrive(const FileName: string): string; Description: Extract Errors: 313 15.4. FILE HANDLING FUNCTIONS See also: ExtractFileName (314), ExtractFilePath (314), ExtractFileDir (313), ExtractFileDrive (313), ExtractFileExt (314), ExtractRelativePath (315) For an example, see ExtractFileDir (313). ExtractFileExt Declaration: Function ExtractFileExt(const FileName: string): string; Description: ExtractFileExt returns the extension (including the .(dot) character) of FileName. Errors: None. See also: ExtractFileName (314), ExtractFilePath (314), ExtractFileDir (313), ExtractFileDrive (313), ExtractFileExt (314), ExtractRelativePath (315) For an example, see ExtractFileDir (313). ExtractFileName Declaration: Function ExtractFileName(const FileName: string): string; Description: ExtractFileName returns the filename part from FileName. The filename consists of all characters after the last directory separator character ('/' or '´) or drive letter. The full filename can always be reconstucted by concatenating the result of Extract- FilePath (314) and ExtractFileName. Errors: None. See also: ExtractFileName (314), ExtractFilePath (314), ExtractFileDir (313), ExtractFileDrive (313), ExtractFileExt (314),ExtractRelativePath (315) For an example, see ExtractFileDir (313). ExtractFilePath Declaration: Function ExtractFilePath(const FileName: string): string; Description: ExtractFilePath returns the path part (including driveletter) from FileName. The path consists of all characters before the last directory separator character ('/' or '´), including the directory separator itself. In case there is only a drive letter, that will be returned. The full filename can always be reconstucted by concatenating the result of ExtractFilePath and ExtractFileName (314). Errors: None. See also: ExtractFileName (314), ExtractFilePath (314), ExtractFileDir (313), ExtractFileDrive (313), ExtractFileExt (314), ExtractRelativePath (315) For an example, see ExtractFileDir (313). 314 15.4. FILE HANDLING FUNCTIONS ExtractRelativePath Declaration: Function ExtractRelativePath(Const BaseName,DestNAme : String): String; Description: ExtractRelativePath constructs a relative path to go from BaseName to DestName. If DestName is on another drive (Not on Linux) then the whole Destname is returned. Note: This function does not exist in the Delphi unit. Errors: None. See also: ExtractFileName (314), ExtractFilePath (314), ExtractFileDir (313), ExtractFileDrive (313), ExtractFileExt (314), Program Example35 ; { This program demonstrates the E x t r a c t R e l a t i v e P a t h f u n c t i o n } Uses s y s u t i l s ; Procedure T e s t i t ( FromDir , ToDir : String ) ; begin Write ( ' From "' , FromDir , '" to "' , ToDir , '" via "' ) ; Writeln ( E x t r a c t R e l a t i v e P a t h ( FromDir , ToDir ) , ' " ' ) ; end ; Begin T e s t i t ( '/ pp/ src / compiler ' , '/ pp/ bin / win32 / ppc386 ' ) ; T e s t i t ( '/ pp/ bin / win32 / ppc386 ' , '/ pp/ src / compiler ' ) ; T e s t i t ( ' e :/ pp/ bin / win32 / ppc386 ' , ' d :/ pp/ src / compiler ' ) ; T e s t i t ( ' e :\ pp\ bin \ win32 \ ppc386 ' , ' d :\ pp\ src \ compiler ' ) ; End. FileAge Declaration: Function FileAge(Const FileName : String): Longint; Description: FileAge returns the last modification time of file FileName. The FileDate for- mat can be transformed to TDateTime format with the FileDateToDateTime (300) function. Errors: In case of errors, -1 is returned. See also: FileDateToDateTime (300), FileExists (317), FileGetAttr (317) Program Example36 ; { This program demonstrates the FileAge f u n c t i o n } Uses s y s u t i l s ; Var S : TDateTime ; fa : Longint ; Begin fa := FileAge ( ' ex36 . pp ' ) ; 315 15.4. FILE HANDLING FUNCTIONS I f Fa<>-1 then begin S:= FileDateTodateTime ( fa ) ; Writeln ( ' I ' ' m from ' , DateTimeToStr ( S )) end ; End. FileClose Declaration: Procedure FileClose(Handle : Longint); Description: FileClose closes the file handle Handle. After this call, attempting to read or write from the handle will result in an error. Errors: None. See also: FileCreate (316), FileWrite (322), FileOpen (319), FileRead (319), FileTruncate (321), FileSeek (320) For an example, see FileCreate (316) FileCreate Declaration: Function FileCreate(Const FileName : String) : Longint; Description: FileCreate creates a new file with name FileName on the disk and returns a file handle which can be used to read or write from the file with the FileRead (319) and FileWrite (322) functions. If a file with name FileName already existed on the disk, it is overwritten. Errors: If an error occurs (e.g. disk full or non-existent path), the function returns -1. See also: FileClose (316), FileWrite (322), FileOpen (319), FileRead (319), FileTruncate (321), FileSeek (320) Program Example37 ; { This program demonstrates the F i l e C r e a t e f u n c t i o n } Uses s y s u t i l s ; Var I , J , F : Longint ; Begin F:= F i l e C r e a t e ( ' t e s t . dat ' ) ; I f F=-1 then Halt ( 1 ) ; For I :=0 to 100 do F i l e W r i t e ( F, I , SizeOf ( i ) ) ; FileClose ( f ) ; F:= FileOpen ( ' t e s t . dat ' , fmOpenRead ) ; For I :=0 to 100 do begin FileRead ( F, J , SizeOF ( J ) ) ; 316 15.4. FILE HANDLING FUNCTIONS I f J<>I then Writeln ( ' Mismatch at f i l e p o s i t i o n ' , I ) end ; FileSeek ( F , 0 , fsFromBeginning ) ; Randomize ; Repeat FileSeek ( F, Random(100) 4, fsFromBeginning ) ; FileRead ( F, J , SizeOf ( J ) ) ; Writeln ( ' Random read : ' , j ) ; Until J >80; FileClose ( F ) ; F:= FileOpen ( ' t e s t . dat ' , fmOpenWrite ) ; I :=50 SizeOf ( Longint ) ; I f F i l e T r u n c a t e ( F, I ) then Writeln ( ' S u c c e s s F u l l y truncated f i l e to ' , I , ' bytes . ' ) ; FileClose ( F ) ; End. FileExists Declaration: Function FileExists(Const FileName : String) : Boolean; Description: FileExists returns True if a file with name FileName exists on the disk, False otherwise. Errors: None. See also: FileAge (315), FileGetAttr (317), FileSetAttr (321) Program Example38 ; { This program demonstrates the F i l e E x i s t s f u n c t i o n } Uses s y s u t i l s ; Begin I f F i l e E x i s t s ( ParamStr ( 0 ) ) Then Writeln ( ' A l l i s w e l l , I seem to e x i s t . ' ) ; End. FileGetAttr Declaration: Function FileGetAttr(Const FileName : String) : Longint; Description: FileGetAttr returns the attribute settings of file FileName. The attribute is a OR-ed combination of the following constants: faReadOnlyThe file is read-only. faHiddenThe file is hidden. (On linux, this means that the filename starts with a dot) faSysFileThe file is a system file (On linux, this means that the file is a character, block or FIFO file). faVolumeIdVolume Label. Not possible under linux. 317 15.4. FILE HANDLING FUNCTIONS faDirectoryFile is a directory. faArchivefile is an archive. Not possible on linux. Errors: In case of error, -1 is returned. See also: FileSetAttr (321), FileAge (315), FileGetDate (318). Program Example40 ; { This program demonstrates the F i l e G e t A t t r f u n c t i o n } Uses s y s u t i l s ; Procedure T e s t i t ( Name : String ) ; Var F : Longint ; Begin F:= FileGetAttr (Name) ; I f F<>-1 then begin Writeln ( ' Testing : ' , Name) ; I f ( F and faReadOnly )<>0 then Writeln ( ' F i l e i s ReadOnly ' ) ; I f ( F and faHidden )<>0 then Writeln ( ' F i l e i s hidden ' ) ; I f ( F and f a S y s F i l e )<>0 then Writeln ( ' F i l e i s a system f i l e ' ) ; I f ( F and faVolumeID )<>0 then Writeln ( ' F i l e i s a disk l a b e l ' ) ; I f ( F and f a A r c h i v e )<>0 then Writeln ( ' F i l e i s a r t c h i v e f i l e ' ) ; I f ( F and f a D i r e c t o r y )<>0 then Writeln ( ' F i l e i s a d i r e c t o r y ' ) ; end else Writeln ( ' Error reading a t t r i b i t e s of ' , Name) ; end ; begin t e s t i t ( ' ex40 . pp ' ) ; t e s t i t ( ParamStr ( 0 ) ) ; t e s t i t ( ' . ' ) ; t e s t i t ( ' / ' ) ; End. FileGetDate Declaration: Function FileGetDate(Handle : Longint) : Longint; Description: FileGetdate returns the filetime of the opened file with filehandle Handle. It is the same as FileAge (315), with this di erence that FileAge only needs the file name, while FilegetDate needs an open file handle. 318 15.4. FILE HANDLING FUNCTIONS Errors: On error, -1 is returned. See also: FileAge (315) Program Example39 ; { This program demonstrates the FileGetDate f u n c t i o n } Uses s y s u t i l s ; Var F, D : Longint ; Begin F:= F i l e C r e a t e ( ' t e s t . dat ' ) ; D:= FileGetDate (D) ; Writeln ( ' F i l e c r e r a t e d on ' , DateTimeToStr ( FileDateToDateTime (D) ) ) ; FileClose ( F ) ; DeleteFile ( ' t e s t . dat ' ) ; End. FileOpen Declaration: Function FileOpen(Const FileName : string; Mode : Integer) : Longint; Description: FileOpen opens a file with name FileName with mode Mode. Mode can be one of the following constants: fmOpenReadThe file is opened for reading. fmOpenWriteThe file is opened for writing. fmOpenReadWriteThe file is opened for reading and writing. If the file has been successfully opened, it can be read from or written to (depending on the Mode parameter) with the FileRead (319) and FileWrite functions. Remark that you cannot open a file if it doesn't exist yet, i.e. it will not be created for you. If you want tp create a new file, or overwrite an old one, use the FileCreate (316) function. Errors: On Error, -1 is returned. See also: FileClose (316), FileWrite (322), FileCreate (316), FileRead (319), FileTruncate (321), FileSeek (320) For an example, see FileRead (319) FileRead Declaration: Function FileRead(Handle : Longint; Var Buffer; Count : longint) : Longint; Description: FileRead reads Count bytes from file-handle Handle and stores them into Buffer. Bu er must be at least Count bytes long. No checking on this is performed, so be careful not to overwrite any memory. Handle must be the result of a FileOpen (319) call. Errors: On error, -1 is returned. 319 15.4. FILE HANDLING FUNCTIONS See also: FileClose (316), FileWrite (322), FileCreate (316), FileOpen (319), FileTruncate (321), FileSeek (320) For an example, see FileOpen (319) FileSearch Declaration: Function FileSearch(Const Name, DirList : String) : String; Description: FileSearch looks for the file Name in DirList, where dirlist is a list of directories, separated by semicolons or colons. It returns the full filename of the first match found. Errors: On error, an empty string is returned. See also: ExpandFileName (312), FindFirst (322) Program Example41 ; { Program to demonstrate the F i l e S e a r c h f u n c t i o n . } Uses S y s u t i l s ; Const { $ i f d e f l i n u x } FN = ' f i n d ' ; P = ' . : / bin :/ usr / bin ' ; { $ e l s e } FN = ' f i n d . exe ' ; P = ' c :\ dos ; c :\ windows ; c :\ windows \ system ; c :\ windows \ system32 ' ; { $ e n d i f } begin Writeln ( ' f i n d i s in : ' , FileSearch ( FN, P) ) ; end . FileSeek Declaration: Function FileSeek(Handle,Offset,Origin : Longint) : Longint; Description: FileSeek sets the file pointer on position Offset, starting from Origin. Origin can be one of the following values: fsFromBeginningOffset is relative to the first byte of the file. This position is zero-based. i.e. the first byte is at o set 0. fsFromCurrentOffset is relative to the current position. fsFromEndOffset is relative to the end of the file. This means that Offset can only be zero or negative in this case. If successfull, the function returns the new file position, relative to the beginning of the file. Remark: The abovementioned constants do not exist in Delphi. Errors: On error, -1 is returned. 320 15.4. FILE HANDLING FUNCTIONS See also: FileClose (316), FileWrite (322), FileCreate (316), FileOpen (319) FileRead (319), FileTruncate (321) Program Example42 ; { This program demonstrates the F i l e S e t A t t r f u n c t i o n } Uses s y s u t i l s ; Begin I f FileSetAttr ( ' ex40 . pp ' , faReadOnly or faHidden )=0 then Writeln ( ' S u c c e s s f u l l y made f i l e hidden and read -only . ' ) else Writeln ( ' Coulnd ' ' t make f i l e hidden and read -only . ' ) ; End. For an example, see FileCreate (316) FileSetAttr (Not on Linux) Declaration: Function FileSetAttr(Const Filename : String; Attr: longint) : Longint; Description: FileSetAttr sets the attributes of FileName to Attr. If the function was success- ful, 0 is returned, -1 otherwise. Attr can be set to an OR-ed combination of the pre-defined faXXX constants. Errors: On error, -1 is returned (always on linux). See also: FileGetAttr (317), FileGetDate (318), FileSetDate (321). FileSetDate (Not on Linux) Declaration: Function FileSetDate(Handle,Age : Longint) : Longint; Description: FileSetDate sets the file date of the file with handle Handle to Age, where Age is a DOS date-and-time stamp value. The function returns zero of successfull. Errors: On Linux, -1 is always returned, since this is impossible to implement. On Windows and DOS, a negative error code is returned. See also: FileTruncate Declaration: Function FileTruncate(Handle,Size: Longint) : boolean; Description: FileTruncate truncates the file with handle Handle to Size bytes. The file must have been opened for writing prior to this call. The function returns True is suc- cessful, False otherwise. Errors: On error, the function returns False. See also: FileClose (316), FileWrite (322), FileCreate (316), FileOpen (319) FileRead (319), FileSeek (320) For an example, see FileCreate (316). 321 15.4. FILE HANDLING FUNCTIONS FileWrite Declaration: Function FileWrite(Handle : Longint; Var Buffer; Count : Longint) : Longint; Description: FileWrite writes Count bytes from Buffer to the file with handle Handle. Prior to this call, the file must have been opened for writing. Buffer must be at least Count bytes large, or a memory access error may occur. The function returns the number of bytes written, or -1 in case of an error. Errors: In case of error, -1 is returned. See also: FileClose (316), FileCreate (316), FileOpen (319) FileRead (319), FileTruncate (321), FileSeek (320) For an example, see FileCreate (316). FindClose Declaration: Procedure FindClose(Var F : TSearchrec); Description: FindClose ends a series of FindFirst (322)/FindNext (323) calls, and frees any memory used by these calls. It is absolutely necessary to do this call, or huge memory losses may occur. Errors: None. See also: FindFirst (322), FindNext (323). For an example, see FindFirst (322). FindFirst Declaration: Function FindFirst(Const Path : String; Attr : Longint; Var Rslt : TSearchRec) : Longint; Description: FindFirst looks for files that match the name (possibly with wildcards) in Path and attributes Attr. It then fills up the Rslt record with data gathered about the file. It returns 0 if a file matching the specified criteria is found, a nonzero value (-1 on linux) otherwise. The Rslt record can be fed to subsequent calls to FindNext, in order to find other files matching the specifications. remark: A FindFirst call must always be followed by a FindClose (322) call with the same Rslt record. Failure to do so will result in memory loss. Errors: On error the function returns -1 on linux, a nonzero error code on Windows. See also: FindClose (40)FindCloseSys, FindNext (323). Program Example43 ; { This program demonstrates the F i n d F i r s t f u n c t i o n } Uses s y s u t i l s ; 322 15.4. FILE HANDLING FUNCTIONS Var I n f o : TSearchRec ; Count : Longint ; Begin Count :=0; I f FindFirst ( ' . pp ' , f a A n y F i l e , I n f o )=0 then begin Repeat Inc ( Count ) ; With I n f o do Writeln ( Name: 4 0 , Size : 1 5 ) ; Until FindNext ( i n f o )<>0; end ; FindClose ( I n f o ) ; Writeln ( ' F i n i s h e d search . Found ' , Count , ' matches ' ) ; End. FindNext Declaration: Function FindNext(Var Rslt : TSearchRec) : Longint; Description: FindNext finds a next occurrence of a search sequence initiated by FindFirst. If another record matching the criteria in Rslt is found, 0 is returned, a nonzero constant is returned otherwise. remark: The last FindNext call must always be followed by a FindClose call with the same Rslt record. Failure to do so will result in memory loss. Errors: On error (no more file is found), a nonzero constant is returned. See also: FindFirst (322), FindClose (40) For an example, see FindFirst (322) GetDirs Declaration: Function GetDirs(Var DirName : String; Var Dirs : Array of pchar) : Longint; Description: GetDirs splits DirName in a null-byte separated list of directory names, Dirs is an array of PChars, pointing to these directory names. The function returns the number of directories found, or -1 if none were found. DirName must contain only OSDirSeparator as Directory separator chars. Errors: None. See also: ExtractRelativePath (315) Program Example45 ; { This program demonstrates the GetDirs f u n c t i o n } {$H+} Uses s y s u t i l s ; 323 15.4. FILE HANDLING FUNCTIONS Var Dirs : Array [ 0 . . 1 2 7 ] of pchar ; I , Count : l o n g i n t ; Dir , NewDir : String ; Begin Dir := GetCurrentDir ; Writeln ( ' Dir : ' , Dir ) ; NewDir := ' ' ; count := GetDirs ( Dir , Dirs ) ; For I :=0 to Count do begin NewDir :=NewDir+' / ' +StrPas ( Dirs [ I ] ) ; Writeln ( NewDir ) ; end ; End. RenameFile Declaration: Function RenameFile(Const OldName, NewName : String) : Boolean; Description: RenameFile renames a file from OldName to NewName. The function returns True if successful, False otherwise. Remark: you cannot rename across disks or partitions. Errors: On Error, False is returned. See also: DeleteFile (311) Program Example44 ; { This program demonstrates the RenameFile f u n c t i o n } Uses s y s u t i l s ; Var F : Longint ; S : String ; Begin S:= ' Some short f i l e . ' ; F:= F i l e C r e a t e ( ' t e s t . dap ' ) ; F i l e W r i t e ( F, S [ 1 ] , Length ( S ) ) ; FileClose ( F ) ; I f RenameFile ( ' t e s t . dap ' , ' t e s t . dat ' ) then Writeln ( ' S u c c e s s f u l l y renamed f i l e s . ' ) ; End. SetDirSeparators Declaration: Function SetDirSeparators(Const FileName : String) : String; Description: SetDirSeparators returns FileName with all possible DirSeparators replaced by OSDirSeparator. 324 15.5. PCHAR FUNCTIONS Errors: None. See also: ExpandFileName (312), ExtractFilePath (314), ExtractFileDir (313) Program Example47 ; { This program demonstrates the S e t D i r S e p a r a t o r s f u n c t i o n } Uses s y s u t i l s ; Begin Writeln ( S e t D i r S e p a r a t o r s ( '/ pp\ bin / win32 \ ppc386 ' ) ) ; End. 15.5 PChar functions Introduction Most PChar functions are the same as their counterparts in the STRINGS unit. The following functions are the same : 1. StrCat (279) : Concatenates two PChar strings. 2. StrComp (280) : Compares two PChar strings. 3. StrCopy (280) : Copies a PChar string. 4. StrECopy (281) : Copies a PChar string and returns a pointer to the termi- nating null byte. 5. StrEnd (282) : Returns a pointer to the terminating null byte. 6. StrIComp (282) : Case insensitive compare of 2 PChar strings. 7. StrLCat (283) : Appends at most L characters from one PChar to another PChar. 8. StrLComp (283) : Case sensitive compare of at most L characters of 2 PChar strings. 9. StrLCopy (284) : Copies at most L characters from one PChar to another. 10. StrLen (284) : Returns the length (exclusive terminating null byte) of a PChar string. 11. StrLIComp (285) : Case insensitive compare of at most L characters of 2 PChar strings. 12. StrLower (285) : Converts a PChar to all lowercase letters. 13. StrMove (286) : Moves one PChar to another. 14. StrNew (286) : Makes a copy of a PChar on the heap, and returns a pointer to this copy. 15. StrPos (288) : Returns the position of one PChar string in another? 16. StrRScan (288) : returns a pointer to the last occurrence of on PChar string in another one. 325 15.5. PCHAR FUNCTIONS 17. StrScan (288) : returns a pointer to the first occurrence of on PChar string in another one. 18. StrUpper (289) : Converts a PChar to all uppercase letters. The subsequent functions are di erent from their counterparts in STRINGS, al- though the same examples can be used. StrAlloc Declaration: Function StrAlloc(Size: cardinal): PChar; Description: StrAlloc reserves memory on the heap for a string with length Len, terminating #0 included, and returns a pointer to it. Additionally, StrAlloc allocates 4 extra bytes to store the size of the allocated memory. Therefore this function is NOT compatible with the StrAlloc (279) function of the Strings unit. Errors: None. See also: StrBufSize (326), StrDispose (327), StrAlloc (279) For an example, see StrBufSize (326). StrBufSize Declaration: Function StrBufSize(var Str: PChar): cardinal; Description: StrBufSize returns the memory allocated for Str. This function ONLY gives the correct result if Str was allocated using StrAlloc (326). Errors: If no more memory is available, a runtime error occurs. See also: StrAlloc (326).StrDispose (327). Program Example46 ; { This program demonstrates the S t r B u f S i z e f u n c t i o n } {$H+} Uses s y s u t i l s ; Const S = ' Some nice s t r i n g ' ; Var P : Pchar ; Begin P:= S t r A l l o c ( Length ( S)+1); StrPCopy (P, S ) ; Write ( P, ' has length ' , length ( S ) ) ; Writeln ( ' and b u f f e r s i z e ' , S t r B u f S i z e (P) ) ; StrDispose (P) ; End. 326 15.5. PCHAR FUNCTIONS StrDispose Declaration: Procedure StrDispose(var Str: PChar); Description: StrDispose frees any memory allocated for Str. This function will only function correctly if Str has been allocated using StrAlloc (326) from the SYSUTILS unit. Errors: If an invalid pointer is passed, or a pointer not allocated with StrAlloc, an error may occur. See also: StrBufSize (326), StrAlloc (326), StrDispose (281) For an example, see StrBufSize (326). StrPCopy Declaration: Function StrPCopy(Dest: PChar; Source: string): PChar; Description: StrPCopy Converts the Ansistring in Source to a Null-terminated string, and copies it to Dest. Dest needs enough room to contain the string Source, i.e. Length(Source)+1 bytes. Errors: No checking is performed to see whether Dest points to enough memory to contain Source. See also: StrPLCopy (327), StrPCopy (287) For an example, see StrPCopy (287). StrPLCopy Declaration: Function StrPLCopy(Dest: PChar; Source: string; MaxLen: cardinal): PChar; Description: StrPLCopy Converts maximally MaxLen characters of the Ansistring in Source to a Null-terminated string, and copies it to Dest. Dest needs enough room to contain the characters. Errors: No checking is performed to see whether Dest points to enough memory to contain L characters of Source. Errors: See also: StrPCopy (327). StrPas Declaration: Function StrPas(Str: PChar): string; Description: Converts a null terminated string in Str to an Ansitring, and returns this string. This string is NOT truncated at 255 characters as is the Errors: None. See also: StrPas (287). For an example, see StrPas (287). 327 15.6. STRING HANDLING FUNCTIONS 15.6 String handling functions AdjustLineBreaks Declaration: Function AdjustLineBreaks(const S: string): string; Description: AdjustLineBreaks will change all #13 characters with #13#10 on Windows NT and dos. On linux, all #13#10 character pairs are converted to #10 and single #13 characters also. Errors: None. See also: AnsiCompareStr (328), AnsiCompareText (329) Program Example48 ; { This program demonstrates the A d j u s t L i n eBr e a k s f u n c t i o n } Uses s y s u t i l s ; Const S = ' This i s a s t r i n g ' #13' with embedded ' #10' l i n e f e e d and ' + #13' CR c h a r a c t e r s ' ; Begin Writeln ( A d ju s t Li n eB r e a k s ( S ) ) ; End. AnsiCompareStr Declaration: Function AnsiCompareStr(const S1, S2: string): integer; Description: AnsiCompareStr compares two strings and returns the following result: ¡0if S1S2. the comparision takes into account Ansi characters, i.e. it takes care of strange accented characters. Contrary to AnsiCompareText (329), the comparision is case sensitive. Errors: None. See also: AdjustLineBreaks (328), AnsiCompareText (329) Program Example49 ; { This program demonstrates the AnsiCompareStr f u n c t i o n } {$H+} Uses s y s u t i l s ; Procedure T e s t I t ( S1 , S2 : String ) ; 328 15.6. STRING HANDLING FUNCTIONS Var R : Longint ; begin R:= AnsiCompareStr ( S1 , S2 ) ; Write ( ' " ' , S1 , '" i s ' ) ; I f R<0 then write ( ' l e s s than ' ) else I f R=0 then Write ( ' equal to ' ) else Write ( ' l a r g e r than ' ) ; Writeln ( ' " ' , S2 , ' " ' ) ; end ; Begin T e s t i t ( ' One s t r i n g ' , ' One s m a l l e r s t r i n g ' ) ; T e s t i t ( ' One s t r i n g ' , ' one s t r i n g ' ) ; T e s t i t ( ' One s t r i n g ' , ' One s t r i n g ' ) ; T e s t i t ( ' One s t r i n g ' , ' One t a l l s t r i n g ' ) ; End. AnsiCompareText Declaration: Function AnsiCompareText(const S1, S2: string): integer; Description: Description: AnsiCompareText compares two strings and returns the following result: ¡0if S1S2. the comparision takes into account Ansi characters, i.e. it takes care of strange accented characters. Contrary to AnsiCompareStr (328), the comparision is case insensitive. Errors: None. See also: AdjustLineBreaks (328), AnsiCompareText (329) Program Example49 ; { This program demonstrates the AnsiCompareText f u n c t i o n } {$H+} Uses s y s u t i l s ; Procedure T e s t I t ( S1 , S2 : String ) ; Var R : Longint ; begin R:=AnsiCompareText ( S1 , S2 ) ; 329 15.6. STRING HANDLING FUNCTIONS Write ( ' " ' , S1 , '" i s ' ) ; I f R<0 then write ( ' l e s s than ' ) else I f R=0 then Write ( ' equal to ' ) else Write ( ' l a r g e r than ' ) ; Writeln ( ' " ' , S2 , ' " ' ) ; end ; Begin T e s t i t ( ' One s t r i n g ' , ' One s m a l l e r s t r i n g ' ) ; T e s t i t ( ' One s t r i n g ' , ' one s t r i n g ' ) ; T e s t i t ( ' One s t r i n g ' , ' One s t r i n g ' ) ; T e s t i t ( ' One s t r i n g ' , ' One t a l l s t r i n g ' ) ; End. AnsiExtractQuotedStr Declaration: Function AnsiExtractQuotedStr(var Src: PChar; Quote: Char): string; Description: AnsiExtractQuotedStr Returns Src as a string,, with Quute characters removed from the beginning and end of the string, and double Quote characters replaced by a single Quote characters. As such, it revereses the action of AnsiQuotedStr (331). Errors: None. See also: AnsiQuotedStr (331) Program Example51 ; { This program demonstrates the AnsiQuotedStr f u n c t i o n } Uses s y s u t i l s ; Var S : A n s i S t r i n g ; Begin S:= ' He s a i d " Hello " and walked on ' ; S:= AnsiQuotedStr ( Pchar ( S ) , ' " ' ) ; Writeln ( S ) ; Writeln ( AnsiExtractQuotedStr ( Pchar ( S ) , ' " ' ) ) ; End. AnsiLastChar Declaration: Function AnsiLastChar(const S: string): PChar; Description: This function returns a pointer to the last character of S. Since multibyte charac- ters are not yet supported, this is the same as @S[Length(S)]). Errors: None. See also: AnsiStrLastChar (333) 330 15.6. STRING HANDLING FUNCTIONS Program Example52 ; { This program demonstrates the AnsiLastChar f u n c t i o n } Uses s y s u t i l s ; Var S : A n s i S t r i n g ; L : Longint ; Begin S:= ' This i s an a n s i s t r i n g . ' ; Writeln ( ' Last c h a r a c t e r of S i s : ' , AnsiLastChar ( S ) ) ; L:= Longint ( AnsiLastChar ( S))- Longint ( @S[ 1 ] ) + 1 ; Writeln ( ' Length of S i s : ' , L ) ; End. AnsiLowerCase Declaration: Function AnsiLowerCase(const s: string): string; Description: AnsiLowerCase converts the string S to lowercase characters and returns the re- sulting string. It takes into account the operating system language settings when doing this, so spcial characters are converted correctly as well. Remark On linux, no language setting is taken in account yet. Errors: None. See also: AnsiUpperCase (337), AnsiStrLower (336), AnsiStrUpper (336) Program Example53 ; { This program demonstrates the AnsiLowerCase f u n c t i o n } Uses s y s u t i l s ; Procedure T e s t i t ( S : String ) ; begin Writeln ( S , ' -> ' , AnsiLowerCase ( S )) end ; Begin T e s t i t ( ' AN UPPERCASE STRING ' ) ; T e s t i t ( ' Some mixed STring ' ) ; T e s t i t ( ' a l o w e r c a s e s t r i n g ' ) ; End. AnsiQuotedStr Declaration: Function AnsiQuotedStr(const S: string; Quote: char): string; Description: AnsiQuotedString quotes the string S and returns the result. This means that it puts the Quote character at both the beginning and end of the string and re- places any occurrence of Quote in S with 2 Quote characters. The action of AnsiQuotedString can be reversed by AnsiExtractQuotedStr (330). 331 15.6. STRING HANDLING FUNCTIONS Errors: None. See also: AnsiExtractQuotedStr (330) For an example, see AnsiExtractQuotedStr (330) AnsiStrComp Declaration: Function AnsiStrComp(S1, S2: PChar): integer; Description: AnsiStrComp compares 2 PChar strings, and returns the following result: ¡0if S1S2. The comparision of the two strings is case-sensitive. The function does not yet take internationalization settings into account. Errors: None. See also: AnsiCompareText (329), AnsiCompareStr (328) Program Example54 ; { This program demonstrates the AnsiStrComp f u n c t i o n } Uses s y s u t i l s ; Procedure T e s t I t ( S1 , S2 : Pchar ) ; Var R : Longint ; begin R:= AnsiStrComp ( S1 , S2 ) ; Write ( ' " ' , S1 , '" i s ' ) ; I f R<0 then write ( ' l e s s than ' ) else I f R=0 then Write ( ' equal to ' ) else Write ( ' l a r g e r than ' ) ; Writeln ( ' " ' , S2 , ' " ' ) ; end ; Begin T e s t i t ( ' One s t r i n g ' , ' One s m a l l e r s t r i n g ' ) ; T e s t i t ( ' One s t r i n g ' , ' one s t r i n g ' ) ; T e s t i t ( ' One s t r i n g ' , ' One s t r i n g ' ) ; T e s t i t ( ' One s t r i n g ' , ' One t a l l s t r i n g ' ) ; End. 332 15.6. STRING HANDLING FUNCTIONS AnsiStrIComp Declaration: Function AnsiStrIComp(S1, S2: PChar): integer; Description: AnsiStrIComp compares 2 PChar strings, and returns the following result: ¡0if S1S2. The comparision of the two strings is case-insensitive. The function does not yet take internationalization settings into account. Errors: None. See also: AnsiCompareText (329), AnsiCompareStr (328) Program Example55 ; { This program demonstrates the AnsiStrIComp f u n c t i o n } Uses s y s u t i l s ; Procedure T e s t I t ( S1 , S2 : Pchar ) ; Var R : Longint ; begin R:= AnsiStrIComp ( S1 , S2 ) ; Write ( ' " ' , S1 , '" i s ' ) ; I f R<0 then write ( ' l e s s than ' ) else I f R=0 then Write ( ' equal to ' ) else Write ( ' l a r g e r than ' ) ; Writeln ( ' " ' , S2 , ' " ' ) ; end ; Begin T e s t i t ( ' One s t r i n g ' , ' One s m a l l e r s t r i n g ' ) ; T e s t i t ( ' One s t r i n g ' , ' one s t r i n g ' ) ; T e s t i t ( ' One s t r i n g ' , ' One s t r i n g ' ) ; T e s t i t ( ' One s t r i n g ' , ' One t a l l s t r i n g ' ) ; End. AnsiStrLastChar Declaration: function AnsiStrLastChar(Str: PChar): PChar; Declaration: AnsiStrLastChar returns a pointer to the last character of Str. Since multibyte characters are not yet supported, this is the same as StrEnd(Str)-1. Errors: None. See also: AnsiLastChar (330) 333 15.6. STRING HANDLING FUNCTIONS Program Example58 ; { This program demonstrates the AnsiStrLastChar f u n c t i o n } Uses s y s u t i l s ; Var P : Pchar ; L : Longint ; Begin P:= ' This i s an PChar s t r i n g . ' ; Writeln ( ' Last c h a r a c t e r of P i s : ' , AnsiStrLas tChar (P) ) ; L:= Longint ( AnsiStrLastChar (P))- Longint (P)+1; Writeln ( ' Length of P ( ' , P, ' ) i s : ' , L ) ; End. AnsiStrLComp Declaration: Function AnsiStrLComp(S1, S2: PChar; MaxLen: cardinal): integer; Description: AnsiStrLComp compares the first Maxlen characters of 2 PChar strings, S1 and S2, and returns the following result: ¡0if S1S2. The comparision of the two strings is case-sensitive. The function does not yet take internationalization settings into account. Errors: None. See also: AnsiCompareText (329), AnsiCompareStr (328) Program Example56 ; { This program demonstrates the AnsiStrLComp f u n c t i o n } Uses s y s u t i l s ; Procedure T e s t I t ( S1 , S2 : Pchar ; L : l o n g i n t ) ; Var R : Longint ; begin R:= AnsiStrLComp ( S1 , S2 , L ) ; Write ( ' F i r s t ' , L , ' c h a r a c t e r s of "' , S1 , '" are ' ) ; I f R<0 then write ( ' l e s s than ' ) else I f R=0 then Write ( ' equal to ' ) else Write ( ' l a r g e r than ' ) ; Writeln ( ' those of "' , S2 , ' " ' ) ; 334 15.6. STRING HANDLING FUNCTIONS end ; Begin T e s t i t ( ' One s t r i n g ' , ' One s m a l l e r s t r i n g ' , 2 5 5 ) ; T e s t i t ( ' One s t r i n g ' , ' One S t r i n g ' , 4 ) ; T e s t i t ( ' One s t r i n g ' , '1 s t r i n g ' , 0 ) ; T e s t i t ( ' One s t r i n g ' , ' One s t r i n g . ' , 9 ) ; End. AnsiStrLIComp Declaration: Function AnsiStrLIComp(S1, S2: PChar; MaxLen: cardinal): integer; Description: AnsiStrLIComp compares the first Maxlen characters of 2 PChar strings, S1 and S2, and returns the following result: ¡0if S1S2. The comparision of the two strings is case-insensitive. The function does not yet take internationalization settings into account. Errors: None. See also: AnsiCompareText (329), AnsiCompareStr (328) Program Example57 ; { This program demonstrates the AnsiStrLIComp f u n c t i o n } Uses s y s u t i l s ; Procedure T e s t I t ( S1 , S2 : Pchar ; L : l o n g i n t ) ; Var R : Longint ; begin R:= AnsiStrLIComp ( S1 , S2 , L ) ; Write ( ' F i r s t ' , L , ' c h a r a c t e r s of "' , S1 , '" are ' ) ; I f R<0 then write ( ' l e s s than ' ) else I f R=0 then Write ( ' equal to ' ) else Write ( ' l a r g e r than ' ) ; Writeln ( ' those of "' , S2 , ' " ' ) ; end ; Begin T e s t i t ( ' One s t r i n g ' , ' One s m a l l e r s t r i n g ' , 2 5 5 ) ; T e s t i t ( ' ONE STRING ' , ' one S t r i n g ' , 4 ) ; T e s t i t ( ' One s t r i n g ' , '1 STRING ' , 0 ) ; T e s t i t ( ' One STRING ' , ' one s t r i n g . ' , 9 ) ; End. 335 15.6. STRING HANDLING FUNCTIONS AnsiStrLower Declaration: Function AnsiStrLower(Str: PChar): PChar; Description: AnsiStrLower converts the PChar Str to lowercase characters and returns the resulting pchar. Note that Str itself is modified, not a copy, as in the case of AnsiLowerCase (331). It takes into account the operating system language settings when doing this, so spcial characters are converted correctly as well. Remark On linux, no language setting is taken in account yet. Errors: None. See also: AnsiStrUpper (336), AnsiLowerCase (331) Program Example59 ; { This program demonstrates the AnsiStrLower f u n c t i o n } Uses s y s u t i l s ; Procedure T e s t i t ( S : Pchar ) ; begin Writeln ( S , ' -> ' , AnsiStrLower ( S )) end ; Begin T e s t i t ( ' AN UPPERCASE STRING ' ) ; T e s t i t ( ' Some mixed STring ' ) ; T e s t i t ( ' a l o w er c a s e s t r i n g ' ) ; End. AnsiStrUpper Declaration: Function AnsiStrUpper(Str: PChar): PChar; Description: AnsiStrUpper converts the PChar Str to uppercase characters and returns the resulting string. Note that Str itself is modified, not a copy, as in the case of AnsiUpperCase (337). It takes into account the operating system language settings when doing this, so spcial characters are converted correctly as well. Remark On linux, no language setting is taken in account yet. Errors: None. See also: AnsiUpperCase (337), AnsiStrLower (336), AnsiLowerCase (331) Program Example60 ; { This program demonstrates the AnsiStrUpper f u n c t i o n } Uses s y s u t i l s ; Procedure T e s t i t ( S : Pchar ) ; begin 336 15.6. STRING HANDLING FUNCTIONS Writeln ( S , ' -> ' , AnsiStrUpper ( S )) end ; Begin T e s t i t ( ' AN UPPERCASE STRING ' ) ; T e s t i t ( ' Some mixed STring ' ) ; T e s t i t ( ' a l o w e r c a s e s t r i n g ' ) ; End. AnsiUpperCase Declaration: Function AnsiUpperCase(const s: string): string; Description: AnsiUpperCase converts the string S to uppercase characters and returns the resulting string. It takes into account the operating system language settings when doing this, so spcial characters are converted correctly as well. Remark On linux, no language setting is taken in account yet. Errors: None. See also: AnsiStrUpper (336), AnsiStrLower (336), AnsiLowerCase (331) Program Example60 ; { This program demonstrates the AnsiUpperCase f u n c t i o n } Uses s y s u t i l s ; Procedure T e s t i t ( S : String ) ; begin Writeln ( S , ' -> ' , AnsiUpperCase ( S )) end ; Begin T e s t i t ( ' AN UPPERCASE STRING ' ) ; T e s t i t ( ' Some mixed STring ' ) ; T e s t i t ( ' a l o w e r c a s e s t r i n g ' ) ; End. AppendStr Declaration: Procedure AppendStr(var Dest: String; const S: string); Description: AppendStr appends S to Dest. This function is provided for Delphi compatibility only, since it is completely equiv- alent to Dest:=Dest+S. Errors: None. See also: AssignStr (338),NewStr (206), DisposeStr (207) 337 15.6. STRING HANDLING FUNCTIONS Program Example62 ; { This program demonstrates the AppendStr f u n c t i o n } Uses s y s u t i l s ; Var S : A n s i S t r i n g ; Begin S:= ' This i s an ' ; AppendStr ( S , ' A n s i S t r i n g ' ) ; Writeln ( ' S = "' , S , ' " ' ) ; End. AssignStr Declaration: Procedure AssignStr(var P: PString; const S: string); Description: AssignStr allocates S to P. The old value of P is disposed of. This function is provided for Delphi compatibility only. AnsiStrings are managed on the heap and should be preferred to the mechanism of dynamically allocated strings. Errors: None. See also: NewStr (206), AppendStr (337), DisposeStr (207) Program Example63 ; { This program demonstrates the A s s i g n S t r f u n c t i o n } {$H+} Uses s y s u t i l s ; Var P : PString ; Begin P:=NewStr( ' A f i r s t A n s i S t r i n g ' ) ; Writeln ( ' Before : P = "' , P , ' " ' ) ; A s s i g n S t r (P, ' A Second a n s i s t r i n g ' ) ; Writeln ( ' After : P = "' , P , ' " ' ) ; DisposeStr (P) ; End. BCDToInt Declaration: Function BCDToInt(Value: integer): integer; Description: BCDToInt converts a BCD coded integer to a normal integer. Errors: None. See also: StrToInt (356), IntToStr (352) 338 15.6. STRING HANDLING FUNCTIONS Program Example64 ; { This program demonstrates the BCDToInt f u n c t i o n } Uses s y s u t i l s ; Procedure T e s t i t ( L : l o n g i n t ) ; begin Writeln ( L , ' -> ' , BCDToInt ( L ) ) ; end ; Begin T e s t i t ( 1 0 ) ; T e s t i t ( 1 0 0 ) ; T e s t i t (1000); End. CompareMem Declaration: Function CompareMem(P1, P2: Pointer; Length: cardinal): integer; Description: CompareMem compares, byte by byte, 2 memory areas pointed to by P1 and P2, for a length of L bytes. It returns the following values: ¡0if at some position the byte at P1 is less than the byte at the same postion at P2. 0if all L bytes are the same. 3 Errors: See also: CompareStr Declaration: Function CompareStr(const S1, S2: string): Integer; Description: CompareStr compares two strings, S1 and S2, and returns the following result: ¡0if S1S2. The comparision of the two strings is case-sensitive. The function does not take internationalization settings into account, it simply compares ASCII values. Errors: None. See also: AnsiCompareText (329), AnsiCompareStr (328), CompareText (340) Program Example65 ; { This program demonstrates the CompareStr f u n c t i o n } {$H+} 339 15.6. STRING HANDLING FUNCTIONS Uses s y s u t i l s ; Procedure T e s t I t ( S1 , S2 : String ) ; Var R : Longint ; begin R:= CompareStr ( S1 , S2 ) ; Write ( ' " ' , S1 , '" i s ' ) ; I f R<0 then write ( ' l e s s than ' ) else I f R=0 then Write ( ' equal to ' ) else Write ( ' l a r g e r than ' ) ; Writeln ( ' " ' , S2 , ' " ' ) ; end ; Begin T e s t i t ( ' One s t r i n g ' , ' One s m a l l e r s t r i n g ' ) ; T e s t i t ( ' One s t r i n g ' , ' one s t r i n g ' ) ; T e s t i t ( ' One s t r i n g ' , ' One s t r i n g ' ) ; T e s t i t ( ' One s t r i n g ' , ' One t a l l s t r i n g ' ) ; End. CompareText Declaration: Function CompareText(const S1, S2: string): integer; Description: CompareText compares two strings, S1 and S2, and returns the following result: ¡0if S1S2. The comparision of the two strings is case-insensitive. The function does not take internationalization settings into account, it simply compares ASCII values. Errors: None. See also: AnsiCompareText (329), AnsiCompareStr (328), CompareStr (339) Program Example66 ; { This program demonstrates the CompareText f u n c t i o n } {$H+} Uses s y s u t i l s ; Procedure T e s t I t ( S1 , S2 : String ) ; Var R : Longint ; 340 15.6. STRING HANDLING FUNCTIONS begin R:= CompareText ( S1 , S2 ) ; Write ( ' " ' , S1 , '" i s ' ) ; I f R<0 then write ( ' l e s s than ' ) else I f R=0 then Write ( ' equal to ' ) else Write ( ' l a r g e r than ' ) ; Writeln ( ' " ' , S2 , ' " ' ) ; end ; Begin T e s t i t ( ' One s t r i n g ' , ' One s m a l l e r s t r i n g ' ) ; T e s t i t ( ' One s t r i n g ' , ' one s t r i n g ' ) ; T e s t i t ( ' One s t r i n g ' , ' One s t r i n g ' ) ; T e s t i t ( ' One s t r i n g ' , ' One t a l l s t r i n g ' ) ; End. DisposeStr Declaration: Procedure DisposeStr(S: PString); Description: DisposeStr removes the dynamically allocated string S from the heap, and releases the occupied memory. This function is provided for Delphi compatibility only. AnsiStrings are managed on the heap and should be preferred to the mechanism of dynamically allocated strings. Errors: None. See also: NewStr (206), AppendStr (337), AssignStr (338) For an example, see DisposeStr (207). FloatToStr Declaration: Function FloatToStr(Value: Extended): String; Description: FloatToStr converts the floating point variable Value to a string representation. It will choose the shortest possible notation of the two following formats: Fixed formatwill represent the string in fixed notation, Decimal formatwill represent the string in scientific notation. (more information on these formats can be found in FloatToStrF (342)) FloatToStr is completely equivalent to a FloatToStrF(Value, ffGeneral, 15, 0); call. Errors: None. See also: FloatToStrF (342) 341 15.6. STRING HANDLING FUNCTIONS Program Example67 ; { This program demonstrates the FloatToStr f u n c t i o n } Uses s y s u t i l s ; Procedure T e s t i t ( Value : Extended ) ; begin Writeln ( Value , ' -> ' , FloatToStr ( Value ) ) ; Writeln (- Value , ' -> ' , FloatToStr (-Value ) ) ; end ; Begin T e s t i t ( 0 . 0 ) ; T e s t i t ( 1 . 1 ) ; T e s t i t ( 1 . 1 e -3); T e s t i t ( 1 . 1 e -20); T e s t i t ( 1 . 1 e -200); T e s t i t ( 1 . 1 e +3); T e s t i t ( 1 . 1 e +20); T e s t i t ( 1 . 1 e +200); End. FloatToStrF Declaration: Function FloatToStrF(Value: Extended; format: TFloatFormat; Precision, Digits: Integer): String; Description: FloatToStrF converts the floating point number value to a string representation, according to the settings of the parameters Format, Precision and Digits. The meaning of the Precision and Digits parameter depends on the Format parameter. The format is controlled mainly by the Format parameter. It can have one of the following values: currencyMoney format. Value is converted to a string using the global variables CurrencyString, CurrencyFormat and NegCurrencyFormat. The Digits paramater specifies the number of digits following the decimal point and should be in the range -1 to 18. If Digits equals -1, CurrencyDecimals is assumed. The Precision parameter is ignored. ExponentScientific format. Value is converted to a string using scientific nota- tion: 1 digit before the decimal point, possibly preceded by a minus sign if Value is negative. The number of digits after the decimal point is controlled by Precision and must lie in the range 0 to 15. FixedFixed point format. Value is converted to a string using fixed point no- tation. The result is composed of all digits of the integer part of Value, preceded by a minus sign if Value is negative. Following the integer part is DecimalSeparator and then the fractional part of Value, rounded o to Digits numbers. If the number is too large then the result will be in scientific notation. GeneralGeneral number format. The argument is converted to a string using ffExponent or ffFixed format, depending on wich one gives the shortest 342 15.6. STRING HANDLING FUNCTIONS string. There will be no trailing zeroes. If Value is less than 0.00001 or if the number of decimals left of the decimal point is larger than Precision then scientific notation is used, and Digits is the minimum number of digits in the exponent. Otherwise Digits is ignored. numberIs the same as ffFixed, except that thousand separators are inserted in the resultig string. Errors: None. See also: FloatToStr (341), FloatToText (344) Program Example68 ; { This program demonstrates the FloatToStrF f u n c t i o n } Uses s y s u t i l s ; Const Fmt : Array [ TFloatFormat ] of stri ng [10] = ( ' g e n e r a l ' , ' exponent ' , ' f i x e d ' , ' number ' , ' Currency ' ) ; Procedure T e s t i t ( Value : Extended ) ; Var I , J : l o n g i n t ; FF : TFloatFormat ; begin For I :=5 to 15 do For J :=1 to 4 do For FF:= f f g e n e r a l to f f c u r r e n c y do begin Write ( Value , ' ( Prec : ' , I : 2 , ' , Dig : ' , J , ' , fmt : ' , Fmt [ f f ] , ' ) : ' ) ; Writeln ( FloatToStrf ( Value , FF , I , J ) ) ; Write (- Value , ' ( Prec : ' , I : 2 , ' , Dig : ' , J , ' , fmt : ' , Fmt [ f f ] , ' ) : ' ) ; Writeln ( FloatToStrf (-Value , FF , I , J ) ) ; end ; end ; Begin T e s t i t ( 1 . 1 ) ; T e s t i t ( 1 . 1 E1 ) ; T e s t i t ( 1 . 1 E-1); T e s t i t ( 1 . 1 E5 ) ; T e s t i t ( 1 . 1 E-5); T e s t i t ( 1 . 1 E10 ) ; T e s t i t ( 1 . 1 E-10); T e s t i t ( 1 . 1 E15 ) ; T e s t i t ( 1 . 1 E-15); T e s t i t ( 1 . 1 E100 ) ; T e s t i t ( 1 . 1 E-100); End. 343 15.6. STRING HANDLING FUNCTIONS FloatToText Declaration: Function FloatToText(Buffer : Pchar;Value: Extended; Format: TFloatFormat; Precision, Digits: Integer): Longint; Description: FloatToText converts the floating point variable Value to a string representation and stores it in Buffer. The conversion is giverned by format, Precisison and Digits. more information on these parameters can be found in FloatToStrF (342). Buffer should point to enough space to hold the result. No checking on this is performed. The result is the number of characters that was copied in Buffer. Errors: None. See also: FloatToStr (341), FloatToStrF (342) Program Example68 ; { This program demonstrates the FloatToStrF f u n c t i o n } Uses s y s u t i l s ; Const Fmt : Array [ TFloatFormat ] of st ri ng [10] = ( ' g e n e r a l ' , ' exponent ' , ' f i x e d ' , ' number ' , ' Currency ' ) ; Procedure T e s t i t ( Value : Extended ) ; Var I , J : l o n g i n t ; FF : TFloatFormat ; S : S h o r t S t r i n g ; begin For I :=5 to 15 do For J :=1 to 4 do For FF:= f f g e n e r a l to f f c u r r e n c y do begin Write ( Value , ' ( Prec : ' , I : 2 , ' , Dig : ' , J , ' , fmt : ' , Fmt [ f f ] , ' ) : ' ) ; SetLength ( S , FloatToText ( @S [ 1 ] , Value , FF , I , J ) ) ; Writeln ( S ) ; Write (- Value , ' ( Prec : ' , I : 2 , ' , Dig : ' , J , ' , fmt : ' , Fmt [ f f ] , ' ) : ' ) ; SetLength ( S , FloatToText ( @S[1],- Value , FF , I , J ) ) ; Writeln ( S ) ; end ; end ; Begin T e s t i t ( 1 . 1 ) ; T e s t i t ( 1 . 1 E1 ) ; T e s t i t ( 1 . 1 E-1); T e s t i t ( 1 . 1 E5 ) ; T e s t i t ( 1 . 1 E-5); T e s t i t ( 1 . 1 E10 ) ; T e s t i t ( 1 . 1 E-10); T e s t i t ( 1 . 1 E15 ) ; T e s t i t ( 1 . 1 E-15); 344 15.6. STRING HANDLING FUNCTIONS T e s t i t ( 1 . 1 E100 ) ; T e s t i t ( 1 . 1 E-100); End. FmtStr Declaration: Procedure (Var Res: String; Const Fmt : String; Const args: Array of const); Description: FmtStr calls Format (345) with Fmt and Args as arguments, and stores the result in Res. For more information on how the resulting string is composed, see Format (345). Errors: In case of error, a EConvertError exception is raised. See also: Format (345), FormatBuf (351). Program Example70 ; { This program demonstrates the FmtStr f u n c t i o n } Uses s y s u t i l s ; Var S : A n s i S t r i n g ; Begin S:= ' ' ; FmtStr ( S , ' For some nice examples of fomatting see %s . ' , [ ' Format ' ] ) ; Writeln ( S ) ; End. Format Declaration: Function Format(Const Fmt : String; const Args : Array of const) : String; Description: Format replaces all placeholders inFmt with the arguments passed in Args and returns the resulting string. A placeholder looks as follows: '%' [Index':'] ['-'] [Width] ['.' Precision] ArgType elements between single quotes must be typed as shown without the quotes, and elements between square brackets [ ] are optional. The meaning of the di erent elements is shown below: '%'starts the placeholder. If you want to insert a literal % character, then you must insert two of them : %%. Index ':'takes the Index-th element in the argument array as the element to insert. '-'tells Format to left-align the inserted text. The default behaviour is to right-align inserted text. This can only take e ect if the Width element is also specified. Widththe inserted string must have at least have Width characters. If not, the inserted string will be padded with spaces. By default, the string is left- padded, resulting in a right-aligned string. This behaviour can be changed by the '-' character. 345 15.6. STRING HANDLING FUNCTIONS '.' PrecisionIndicates the precision to be used when converting the argument. The exact meaning of this parameter depends on ArgType. The Index, Width and Precision parameters can be replaced by *, in which case their value will be read from the next element in the Args array. This value must be an integer, or an EConvertError exception will be raised. The argument type is determined from ArgType. It can have one of the following values (case insensitive): DDecimal format. The next argument in the Args array should be an integer. The argument is converted to a decimal string,. If precision is specified, then the string will have at least Precision digits in it. If needed, the string is (left) padded with zeroes. Escientific format. The next argument in the Args array should be a Floating point value. The argument is converted to a decimal string using scientific notation, using FloatToStrF (342), where the optional precision is used to specify the total number of decimals. (defalt a valueof 15 is used). The exponent is formatted using maximally 3 digits. In short, the E specifier formats it's arguument as follows: FloatToStrF(Argument,ffexponent,Precision,3) Ffixed point format. The next argument in the Args array should be a floating point value. The argument is converted to a decimal string, using fixed notation (see FloatToStrF (342)). Precision indicates the number of digits following the decimal point. In short, the F specifier formats it's arguument as follows: FloatToStrF(Argument,ffFixed,ffixed,9999,Precision) GGeneral number format. The next argument in the Args array should be a floating point value. The argument is converted to a decimal string using fixed point notation or scientific notation, depending on which gives the shortest result. Precision is used to determine the number of digits after the decimal point. In short, the G specifier formats it's arguument as follows: FloatToStrF(Argument,ffGeneral,Precision,3) MCurrency format. the next argument in the varArgs array must be a floating point value. The argument is converted to a decimal string using currency notation. This means that fixed-point notation is used, but that the cur- rency symbol is appended. If precision is specified, then then it overrides the CurrencyDecimals global variable used in the FloatToStrF (342) In short, the M specifier formats it's arguument as follows: FloatToStrF(Argument,ffCurrency,9999,Precision) NNumber format. This is the same as fixed point format, except that thousand separators are inserted in the resulting string. PPointer format. The next argument in the Args array must be a pointer (typed or untyped). The pointer value is converted to a string of length 8, representing the hexadecimal value of the pointer. SString format. The next argument in the Args array must be a string. The argument is simply copied to the result string. If Precision is specified, then only Precision characters are copied to the result string. 346 15.6. STRING HANDLING FUNCTIONS Xhexadecimal format. The next argument in the Args array must be an integer. The argument is converted to a hexadecimal string with just enough characters to contain the value of the integer. If Precision is specified then the resulting hexadecimal representation will have at least Precision characters in it (with a maximum value of 32). Errors: In case of error, an EConversionError exception is raised. Possible errors are: 1.Errors in the format specifiers. 2.The next argument is not of the type needed by a specifier. 3.The number of arguments is not su cient for all format specifiers. See also: FormatBuf (351) Program example71 ; { This program demonstrates the Format f u n c t i o n } Uses s y s u t i l s ; Var P : Pointer ; fmt , S : str in g ; Procedure T e s t I n t e g e r ; begin TryFmt:='[%d]' ;S:=Format ( Fmt,[10]); writeln (Fmt:12, ' => ' , s ); Fmt:= '[%%]' ; S:=Format ( Fmt , [ 1 0 ] ) ; writeln ( Fmt : 1 2 , ' => ' , s ) ; Fmt:= '[%10 d ] ' ; S:=Format ( Fmt , [ 1 0 ] ) ; writeln ( Fmt : 1 2 , ' => ' , s ) ; fmt := '[%.4 d ] ' ; S:=Format ( fmt , [ 1 0 ] ) ; writeln ( Fmt : 1 2 , ' => ' , s ) ; Fmt:= '[%10.4 d ] ' ; S:=Format ( Fmt , [ 1 0 ] ) ; writeln ( Fmt : 1 2 , ' => ' , s ) ; Fmt:= '[%0: d ] ' ; S:=Format ( Fmt , [ 1 0 ] ) ; writeln ( Fmt : 1 2 , ' => ' , s ) ; Fmt:= '[%0:10 d ] ' ; S:=Format ( Fmt , [ 1 0 ] ) ; writeln ( Fmt : 1 2 , ' => ' , s ) ; Fmt:= ' [ % 0 : 1 0 . 4 d ] ' ; S:=Format ( Fmt , [ 1 0 ] ) ; writeln ( Fmt : 1 2 , ' => ' , s ) ; Fmt:= '[%0:-10 d ] ' ; S:=Format ( Fmt , [ 1 0 ] ) ; writeln ( Fmt : 1 2 , ' => ' , s ) ; Fmt:= '[%0:-10.4 d ] ' ; S:=Format ( fmt , [ 1 0 ] ) ; writeln ( Fmt : 1 2 , ' => ' , s ) ; Fmt:= '[%- . d ] ' ; S:=Format ( fmt , [ 4 , 5 , 1 0 ] ) ; writeln ( Fmt : 1 2 , ' => ' , s ) ; except On E : Exception do begin Writeln ( ' Exception caught : ' , E. Message ) ; end ; end ; writeln ( ' Press enter ' ) ; readln ; end ; Procedure TestHexaDecimal ; begin tryFmt:='[%x ]' ;S:=Format ( Fmt,[10]); writeln (Fmt:12, ' => ' , s ); Fmt:= '[%10 x ] ' ; S:=Format ( Fmt , [ 1 0 ] ) ; writeln ( Fmt : 1 2 , ' => ' , s ) ; 347 15.6. STRING HANDLING FUNCTIONS Fmt:= '[%10.4 x ] ' ; S:=Format ( Fmt , [ 1 0 ] ) ; writeln ( Fmt : 1 2 , ' => ' , s ) ; Fmt:= '[%0: x ] ' ; S:=Format ( Fmt , [ 1 0 ] ) ; writeln ( Fmt : 1 2 , ' => ' , s ) ; Fmt:= '[%0:10 x ] ' ; S:=Format ( Fmt , [ 1 0 ] ) ; writeln ( Fmt : 1 2 , ' => ' , s ) ; Fmt:= ' [ % 0 : 1 0 . 4 x ] ' ; S:=Format ( Fmt , [ 1 0 ] ) ; writeln ( Fmt : 1 2 , ' => ' , s ) ; Fmt:= '[%0:-10 x ] ' ; S:=Format ( Fmt , [ 1 0 ] ) ; writeln ( Fmt : 1 2 , ' => ' , s ) ; Fmt:= '[%0:-10.4 x ] ' ; S:=Format ( fmt , [ 1 0 ] ) ; writeln ( Fmt : 1 2 , ' => ' , s ) ; Fmt:= '[%- . x ] ' ; S:=Format ( fmt , [ 4 , 5 , 1 0 ] ) ; writeln ( Fmt : 1 2 , ' => ' , s ) ; except On E : Exception do begin Writeln ( ' Exception caught : ' , E. Message ) ; end ; end ; writeln ( ' Press enter ' ) ; readln ; end ; Procedure T es tP o i n ter ; begin P:= Pointer (1234567); tryFmt:='[0 x%p]' ;S:=Format ( Fmt,[ P]); writeln (Fmt:12, ' => ' , s ); Fmt:= ' [ 0 x%10p ] ' ; S:=Format ( Fmt , [ P ] ) ; writeln ( Fmt : 1 2 , ' => ' , s ) ; Fmt:= ' [ 0 x %10.4 p ] ' ; S:=Format ( Fmt , [ P ] ) ; writeln ( Fmt : 1 2 , ' => ' , s ) ; Fmt:= ' [ 0 x %0:p ] ' ; S:=Format ( Fmt , [ P ] ) ; writeln ( Fmt : 1 2 , ' => ' , s ) ; Fmt:= ' [ 0 x %0:10 p ] ' ; S:=Format ( Fmt , [ P ] ) ; writeln ( Fmt : 1 2 , ' => ' , s ) ; Fmt:= ' [ 0 x %0:10.4 p ] ' ; S:=Format ( Fmt , [ P ] ) ; writeln ( Fmt : 1 2 , ' => ' , s ) ; Fmt:= ' [ 0 x%0:-10p ] ' ; S:=Format ( Fmt , [ P ] ) ; writeln ( Fmt : 1 2 , ' => ' , s ) ; Fmt:= ' [ 0 x %0:-10.4 p ] ' ; S:=Format ( fmt , [ P ] ) ; writeln ( Fmt : 1 2 , ' => ' , s ) ; Fmt:= '[%- . p ] ' ; S:=Format ( fmt , [ 4 , 5 , P ] ) ; writeln ( Fmt : 1 2 , ' => ' , s ) ; except On E : Exception do begin Writeln ( ' Exception caught : ' , E. Message ) ; end ; end ; writeln ( ' Press enter ' ) ; readln ; end ; Procedure T e s t S t r i n g ; begin tryFmt:='[%s ]' ;S:=Format(fmt ,[ ' This is a string ' ]); Writeln (fmt :12, '=> ', s ); fmt := '[%0: s ] ' ; s :=Format ( fmt , [ ' This i s a s t r i n g ' ] ) ; Writeln ( fmt : 1 2 , '=> ' , s ) ; fmt := '[%0:18 s ] ' ; s :=Format ( fmt , [ ' This i s a s t r i n g ' ] ) ; Writeln ( fmt : 1 2 , '=> ' , s ) ; fmt := '[%0:-18 s ] ' ; s :=Format ( fmt , [ ' This i s a s t r i n g ' ] ) ; Writeln ( fmt : 1 2 , '=> ' , s ) ; fmt := '[%0:18.12 s ] ' ; s :=Format ( fmt , [ ' This i s a s t r i n g ' ] ) ; Writeln ( fmt : 1 2 , '=> ' , s ) ; fmt := '[%- . s ] ' ; s :=Format ( fmt , [ 1 8 , 1 2 , ' This i s a s t r i n g ' ] ) ; Writeln ( fmt : 1 2 , '=> ' , s ) ; except On E : Exception do begin 348 15.6. STRING HANDLING FUNCTIONS Writeln ( ' Exception caught : ' , E. Message ) ; end ; end ; writeln ( ' Press enter ' ) ; readln ; end ; Procedure T e s t E x p o n e n t i a l ; begin TryFmt:='[%e ]' ;S:=Format ( Fmt,[1.234]); writeln (Fmt:12, ' => ' , s ); Fmt:= '[%10 e ] ' ; S:=Format ( Fmt , [ 1 . 2 3 4 ] ) ; writeln ( Fmt : 1 2 , ' => ' , s ) ; Fmt:= '[%10.4 e ] ' ; S:=Format ( Fmt , [ 1 . 2 3 4 ] ) ; writeln ( Fmt : 1 2 , ' => ' , s ) ; Fmt:= '[%0: e ] ' ; S:=Format ( Fmt , [ 1 . 2 3 4 ] ) ; writeln ( Fmt : 1 2 , ' => ' , s ) ; Fmt:= '[%0:10 e ] ' ; S:=Format ( Fmt , [ 1 . 2 3 4 ] ) ; writeln ( Fmt : 1 2 , ' => ' , s ) ; Fmt:= ' [ % 0 : 1 0 . 4 e ] ' ; S:=Format ( Fmt , [ 1 . 2 3 4 ] ) ; writeln ( Fmt : 1 2 , ' => ' , s ) ; Fmt:= '[%0:-10 e ] ' ; S:=Format ( Fmt , [ 1 . 2 3 4 ] ) ; writeln ( Fmt : 1 2 , ' => ' , s ) ; Fmt:= '[%0:-10.4 e ] ' ; S:=Format ( fmt , [ 1 . 2 3 4 ] ) ; writeln ( Fmt : 1 2 , ' => ' , s ) ; Fmt:= '[%- . e ] ' ; S:=Format ( fmt , [ 4 , 5 , 1 . 2 3 4 ] ) ; writeln ( Fmt : 1 2 , ' => ' , s ) ; except On E : Exception do begin Writeln ( ' Exception caught : ' , E. Message ) ; end ; end ; writeln ( ' Press enter ' ) ; readln ; end ; Procedure T e s t N e g a t i v e E x p o n e n t i a l ; begin TryFmt:='[%e ]' ;S:=Format ( Fmt,[-1.234]); writeln (Fmt:12, ' => ' , s ); Fmt:= '[%10 e ] ' ; S:=Format ( Fmt , [ - 1 . 2 3 4 ] ) ; writeln ( Fmt : 1 2 , ' => ' , s ) ; Fmt:= '[%10.4 e ] ' ; S:=Format ( Fmt , [ - 1 . 2 3 4 ] ) ; writeln ( Fmt : 1 2 , ' => ' , s ) ; Fmt:= '[%0: e ] ' ; S:=Format ( Fmt , [ - 1 . 2 3 4 ] ) ; writeln ( Fmt : 1 2 , ' => ' , s ) ; Fmt:= '[%0:10 e ] ' ; S:=Format ( Fmt , [ - 1 . 2 3 4 ] ) ; writeln ( Fmt : 1 2 , ' => ' , s ) ; Fmt:= ' [ % 0 : 1 0 . 4 e ] ' ; S:=Format ( Fmt , [ - 1 . 2 3 4 ] ) ; writeln ( Fmt : 1 2 , ' => ' , s ) ; Fmt:= '[%0:-10 e ] ' ; S:=Format ( Fmt , [ - 1 . 2 3 4 ] ) ; writeln ( Fmt : 1 2 , ' => ' , s ) ; Fmt:= '[%0:-10.4 e ] ' ; S:=Format ( fmt , [ - 1 . 2 3 4 ] ) ; writeln ( Fmt : 1 2 , ' => ' , s ) ; Fmt:= '[%- . e ] ' ; S:=Format ( fmt , [ 4 , 5 , - 1 . 2 3 4 ] ) ; writeln ( Fmt : 1 2 , ' => ' , s ) ; except On E : Exception do begin Writeln ( ' Exception caught : ' , E. Message ) ; end ; end ; writeln ( ' Press enter ' ) ; readln ; end ; Procedure T e s t S m a l l E x p o n e n t i a l ; 349 15.6. STRING HANDLING FUNCTIONS begin TryFmt:='[%e ]' ;S:=Format ( Fmt,[0.01234]); writeln (Fmt:12, ' => ' , s ); Fmt:= '[%10 e ] ' ; S:=Format ( Fmt , [ 0 . 0 1 2 3 4 ] ) ; writeln ( Fmt : 1 2 , ' => ' , s ) ; Fmt:= '[%10.4 e ] ' ; S:=Format ( Fmt , [ 0 . 0 1 2 3 4 ] ) ; writeln ( Fmt : 1 2 , ' => ' , s ) ; Fmt:= '[%0: e ] ' ; S:=Format ( Fmt , [ 0 . 0 1 2 3 4 ] ) ; writeln ( Fmt : 1 2 , ' => ' , s ) ; Fmt:= '[%0:10 e ] ' ; S:=Format ( Fmt , [ 0 . 0 1 2 3 4 ] ) ; writeln ( Fmt : 1 2 , ' => ' , s ) ; Fmt:= ' [ % 0 : 1 0 . 4 e ] ' ; S:=Format ( Fmt , [ 0 . 0 1 2 3 4 ] ) ; writeln ( Fmt : 1 2 , ' => ' , s ) ; Fmt:= '[%0:-10 e ] ' ; S:=Format ( Fmt , [ 0 . 0 1 2 3 ] ) ; writeln ( Fmt : 1 2 , ' => ' , s ) ; Fmt:= '[%0:-10.4 e ] ' ; S:=Format ( fmt , [ 0 . 0 1 2 3 4 ] ) ; writeln ( Fmt : 1 2 , ' => ' , s ) ; Fmt:= '[%- . e ] ' ; S:=Format ( fmt , [ 4 , 5 , 0 . 0 1 2 3 4 ] ) ; writeln ( Fmt : 1 2 , ' => ' , s ) ; except On E : Exception do begin Writeln ( ' Exception caught : ' , E. Message ) ; end ; end ; writeln ( ' Press enter ' ) ; readln ; end ; Procedure TestSmallNegExponential ; begin TryFmt:='[%e ]' ;S:=Format ( Fmt,[-0.01234]); writeln (Fmt:12, ' => ' , s ); Fmt:= '[%10 e ] ' ; S:=Format ( Fmt , [ - 0 . 0 1 2 3 4 ] ) ; writeln ( Fmt : 1 2 , ' => ' , s ) ; Fmt:= '[%10.4 e ] ' ; S:=Format ( Fmt , [ - 0 . 0 1 2 3 4 ] ) ; writeln ( Fmt : 1 2 , ' => ' , s ) ; Fmt:= '[%0: e ] ' ; S:=Format ( Fmt , [ - 0 . 0 1 2 3 4 ] ) ; writeln ( Fmt : 1 2 , ' => ' , s ) ; Fmt:= '[%0:10 e ] ' ; S:=Format ( Fmt , [ - 0 . 0 1 2 3 4 ] ) ; writeln ( Fmt : 1 2 , ' => ' , s ) ; Fmt:= ' [ % 0 : 1 0 . 4 e ] ' ; S:=Format ( Fmt , [ - 0 . 0 1 2 3 4 ] ) ; writeln ( Fmt : 1 2 , ' => ' , s ) ; Fmt:= '[%0:-10 e ] ' ; S:=Format ( Fmt , [ - 0 . 0 1 2 3 4 ] ) ; writeln ( Fmt : 1 2 , ' => ' , s ) ; Fmt:= '[%0:-10.4 e ] ' ; S:=Format ( fmt , [ - 0 . 0 1 2 3 4 ] ) ; writeln ( Fmt : 1 2 , ' => ' , s ) ; Fmt:= '[%- . e ] ' ; S:=Format ( fmt , [ 4 , 5 , - 0 . 0 1 2 3 4 ] ) ; writeln ( Fmt : 1 2 , ' => ' , s ) ; except On E : Exception do begin Writeln ( ' Exception caught : ' , E. Message ) ; end ; end ; writeln ( ' Press enter ' ) ; readln ; end ; begin T e s t I n t e g e r ; TestHexadecimal ; Tes t Po i nt er ; T e s t E x p o n e n t i a l ; T e s t N e g a t i v e E x p o n e n t i a l ; T e s t S m a l l E x p o n e n t i a l ; TestSmallNegExponential ; end . 350 15.6. STRING HANDLING FUNCTIONS FormatBuf Declaration: Function FormatBuf(Var Buffer; BufLen : Cardinal; Const Fmt; fmtLen : Cardinal; Const Args : Array of const) : Cardinal; Description: Format Errors: See also: Program Example72 ; { This program demonstrates the FormatBuf f u n c t i o n } Uses s y s u t i l s ; VarS : ShortString ; Const Fmt : S h o r t S t r i n g = ' For some nice examples of fomatting see %s . ' ; Begin S:= ' ' ; SetLength ( S , FormatBuf ( S [ 1 ] , 2 5 5 , Fmt [ 1 ] , Length ( Fmt ) , [ ' Format ' ] ) ) ; Writeln ( S ) ; End. IntToHex Declaration: Function IntToHex(Value: integer; Digits: integer): string; Description: IntToHex converts Value to a hexadecimal string representation. The result will contain at least Digits characters. If Digits is less than the needed number of characters, the string will NOT be truncated. If Digits is larger than the needed number of characters, the result is padded with zeroes. Errors: None. See also: IntToStr (352), StrToInt Program Example73 ; { This program demonstrates the IntToHex f u n c t i o n } Uses s y s u t i l s ; Var I : l o n g i n t ; Begin For I :=0 to 31 do begin Writeln ( IntToHex (1 shl I , 8 ) ) ; Writeln ( IntToHex (15 shl I , 8 ) ) end ; End. 351 15.6. STRING HANDLING FUNCTIONS IntToStr Declaration: Function IntToStr(Value: integer): string; Description: IntToStr coverts Value to it's string representation. The resulting string has only as much characters as needed to represent the value. If the value is negative a minus sign is prepended to the string. Errors: None. See also: IntToHex (351), StrToInt (356) Program Example74 ; { This program demonstrates the IntToStr f u n c t i o n } Uses s y s u t i l s ; Var I : l o n g i n t ; Begin For I :=0 to 31 do begin Writeln ( IntToStr (1 shl I ) ) ; Writeln ( IntToStr (15 shl I ) ) ; end ; End. IsValidIdent Declaration: Function IsValidIdent(const Ident: string): boolean; Description: IsValidIdent returns True if Ident can be used as a compoent name. It re- turns False otherwise. Ident must consist of a letter or underscore, followed by a combination of letters, numbers or underscores to be a valid identifier. Errors: None. See also: Program Example75 ; { This program demonstrates the I s V a l i d I d e n t f u n c t i o n } Uses s y s u t i l s ; Procedure T e s t i t ( S : String ) ; begin Write ( ' " ' , S , '" i s ' ) ; I f not IsVAlidIdent ( S ) then Write ( ' NOT ' ) ; Writeln ( ' a v a l i d i d e n t i f i e r ' ) ; end ; Begin 352 15.6. STRING HANDLING FUNCTIONS T e s t i t ( ' MyObj' ) ; T e s t i t ( ' My Obj1' ) ; T e s t i t ( ' My 1 Obj' ) ; T e s t i t ( '1 MyObject ' ) ; T e s t i t ( ' My@Object ' ) ; T e s t i t ( ' M123' ) ; End. LeftStr Declaration: Function LeftStr(const S: string; Count: integer): string; Description: LeftStr returns the Count leftmost characters of S. It is equivalent to a call to Copy(S,1,Count). Errors: None. See also: RightStr (355), TrimLeft (358), TrimRight (358), Trim (357) Program Example76 ; { This program demonstrates the L e f t S t r f u n c t i o n } Uses s y s u t i l s ; Begin Writeln ( L e f t S t r ( ' a b c d e f g h i j k l m n o p q r s t u v w x y z ' , 2 0 ) ) ; Writeln ( L e f t S t r ( ' a b c d e f g h i j k l m n o p q r s t u v w x y z ' , 1 5 ) ) ; Writeln ( L e f t S t r ( ' a b c d e f g h i j k l m n o p q r s t u v w x y z ' , 1 ) ) ; Writeln ( L e f t S t r ( ' a b c d e f g h i j k l m n o p q r s t u v w x y z ' , 2 0 0 ) ) ; End. LoadStr Declaration: Function LoadStr(Ident: integer): string; Description: This function is not yet implemented. resources are not yet supported. Errors: See also: LowerCase Declaration: Function LowerCase(const s: string): string; Description: LowerCase returns the lowercase equivalent of S. Ansi characters are not taken into account, only ASCII codes below 127 are converted. It is completely equivalent to the lowercase function of the system unit, and is provided for compatiibility only. Errors: None. See also: AnsiLowerCase (331), UpperCase (359), AnsiUpperCase (337) 353 15.6. STRING HANDLING FUNCTIONS Program Example77 ; { This program demonstrates the LowerCase f u n c t i o n } Uses s y s u t i l s ; Begin Writeln ( LowerCase ( ' THIS WILL COME out a l l LoWeRcAsE ! ' ) ) ; End. NewStr Declaration: Function NewStr(const S: string): PString; Description: NewStr assigns a new dynamic string on the heap, copies S into it, and returns a pointer to the newly assigned string. This function is obsolete, and shouldn't be used any more. The AnsiString mech- anism also allocates ansistrings on the heap, and should be preferred over this mechanism. Errors: If not enough memory is present, an EOutOfMemory exception will be raised. See also: AssignStr (338), DisposeStr (341) For an example, see AssignStr (338). QuotedStr Declaration: Function QuotedStr(const S: string): string; Description: QuotedStr returns the string S, quoted with single quotes. This means that S is enclosed in single quotes, and every single quote in S is doubled. It is equivalent to a call to AnsiQuotedStr(s, ''''). Errors: None. See also: AnsiQuotedStr (331), AnsiExtractQuotedStr (330). Program Example78 ; { This program demonstrates the QuotedStr f u n c t i o n } Uses s y s u t i l s ; Var S : A n s i S t r i n g ; Begin S:= ' He s a i d ' ' Hello ' ' and walked on ' ; Writeln ( S ) ; Writeln ( ' becomes ' ) ; Writeln ( QuotedStr ( S ) ) ; End. 354 15.6. STRING HANDLING FUNCTIONS RightStr Declaration: Function RightStr(const S: string; Count: integer): string; Description: RightStr returns the Count rightmost characters of S. It is equivalent to a call to Copy(S,Length(S)+1-Count,Count). If Count is larger than the actual length of S only the real length will be used. Errors: None. See also: LeftStr (353),Trim (357), TrimLeft (358), TrimRight (358) Program Example79 ; { This program demonstrates the RightStr f u n c t i o n } Uses s y s u t i l s ; Begin Writeln ( RightStr ( ' a b c d e f g h i j k l m n o p q r s t u v w x y z ' , 2 0 ) ) ; Writeln ( RightStr ( ' a b c d e f g h i j k l m n o p q r s t u v w x y z ' , 1 5 ) ) ; Writeln ( RightStr ( ' a b c d e f g h i j k l m n o p q r s t u v w x y z ' , 1 ) ) ; Writeln ( RightStr ( ' a b c d e f g h i j k l m n o p q r s t u v w x y z ' , 2 0 0 ) ) ; End. StrFmt Declaration: Function StrFmt(Buffer,Fmt : PChar; Const args: Array of const) : Pchar; Description: StrFmt will format fmt with Args, as the Format (345) function does, and it will store the result in Buffer. The function returns Buffer. Buffer should point to enough space to contain the whole result. Errors: for a list of errors, see Format (345). See also: StrLFmt (355), FmtStr (345), Format (345), FormatBuf (351) Program Example80 ; { This program demonstrates the StrFmt f u n c t i o n } Uses s y s u t i l s ; Var S : A n s i S t r i n g ; Begin SetLEngth ( S , 8 0 ) ; Writeln ( StrFmt ( @S [ 1 ] , ' For some nice examples of fomatting see %s . ' , [ ' Format ' ] ) ) ; End. StrLFmt Declaration: Function StrLFmt(Buffer : PCHar; Maxlen : Cardinal;Fmt : PChar; Const args: Array of const) : Pchar; 355 15.6. STRING HANDLING FUNCTIONS Description: StrLFmt will format fmt with Args, as the Format (345) function does, and it will store maximally Maxlen characters of the result in Buffer. The function returns Buffer. Buffer should point to enough space to contain MaxLen characters. Errors: for a list of errors, see Format (345). See also: StrFmt (355), FmtStr (345), Format (345), FormatBuf (351) Program Example80 ; { This program demonstrates the StrFmt f u n c t i o n } Uses s y s u t i l s ; Var S : A n s i S t r i n g ; Begin SetLEngth ( S , 8 0 ) ; Writeln ( StrLFmt ( @S [ 1 ] , 8 0 , ' For some nice examples of fomatting see %s . ' , [ ' Format ' ] ) ) ; End. StrToInt Declaration: Function StrToInt(const s: string): integer; Description: StrToInt will convert the string Sto an integer. If the string contains invalid characters or has an invalid format, then an EConvertError is raised. To be successfully converted, a string can contain a combination of numerical characters, possibly preceded by a minus sign (-). Spaces are not allowed. Errors: In case of error, an EConvertError is raised. See also: IntToStr (352), StrToIntDef (357) Program Example82 ; { This program demonstrates the StrToInt f u n c t i o n } Uses s y s u t i l s ; Begin Writeln ( StrToInt ( ' 1 2 3 4 ' ) ) ; Writeln ( StrToInt ( '-1234' ) ) ; Writeln ( StrToInt ( ' 0 ' ) ) ; TryWriteln ( StrToInt( '12345678901234567890' )); except On E : EConvertError do Writeln ( ' I n v a l i d number encountered ' ) ; end ; End. 356 15.6. STRING HANDLING FUNCTIONS StrToIntDef Declaration: Function StrToIntDef(const S: string; Default: integer): integer; Description: StrToIntDef will convert a string to an integer. If the string contains invalid characters or has an invalid format, then Default is returned. To be successfully converted, a string can contain a combination of numerical characters, possibly preceded by a minus sign (-). Spaces are not allowed. Errors: None. See also: IntToStr (352), StrToInt (356) Program Example82 ; { This program demonstrates the StrToInt f u n c t i o n } Uses s y s u t i l s ; Begin Writeln ( StrToIntDef ( ' 1 2 3 4 ' , 0 ) ) ; Writeln ( StrToIntDef ( '-1234' , 0 ) ) ; Writeln ( StrToIntDef ( ' 0 ' , 0 ) ) ; TryWriteln ( StrToIntDef( '12345678901234567890' ,0)); except On E : EConvertError do Writeln ( ' I n v a l i d number encountered ' ) ; end ; End. Trim Declaration: Function Trim(const S: string): string; Description: Trim strips blank characters (spaces) at the beginning and end of S and returns the resulting string. Only #32 characters are stripped. If the string contains only spaces, an empty string is returned. Errors: None. See also: TrimLeft (358), TrimRight (358) Program Example84 ; { This program demonstrates the Trim f u n c t i o n } Uses s y s u t i l s ; {$H+} Procedure T e s t i t ( S : String ) ; begin Writeln ( ' " ' , Trim ( S ) , ' " ' ) ; end ; 357 15.6. STRING HANDLING FUNCTIONS Begin T e s t i t ( ' ha ha what gets l o s t ? ' ) ; T e s t i t (#10#13 ' haha ' ) ; T e s t i t ( ' ' ) ; End. TrimLeft Declaration: Function TrimLeft(const S: string): string; Description: TrimLeft strips blank characters (spaces) at the beginning of S and returns the resulting string. Only #32 characters are stripped. If the string contains only spaces, an empty string is returned. Errors: None. See also: Trim (357), TrimRight (358) Program Example85 ; { This program demonstrates the TrimLeft f u n c t i o n } Uses s y s u t i l s ; {$H+} Procedure T e s t i t ( S : String ) ; begin Writeln ( ' " ' , TrimLeft ( S ) , ' " ' ) ; end ; Begin T e s t i t ( ' ha ha what gets l o s t ? ' ) ; T e s t i t (#10#13 ' haha ' ) ; T e s t i t ( ' ' ) ; End. TrimRight Declaration: Function TrimRight(const S: string): string; Description: Trim strips blank characters (spaces) at the end of S and returns the resulting string. Only #32 characters are stripped. If the string contains only spaces, an empty string is returned. Errors: None. See also: Trim (357), TrimLeft (358) Program Example86 ; { This program demonstrates the TrimRight f u n c t i o n } 358 15.6. STRING HANDLING FUNCTIONS Uses s y s u t i l s ; {$H+} Procedure T e s t i t ( S : String ) ; begin Writeln ( ' " ' , TrimRight ( S ) , ' " ' ) ; end ; Begin T e s t i t ( ' ha ha what gets l o s t ? ' ) ; T e s t i t (#10#13 ' haha ' ) ; T e s t i t ( ' ' ) ; End. UpperCase Declaration: Function UpperCase(const s: string): string; Description: UpperCase returns the uppercase equivalent of S. Ansi characters are not taken into account, only ASCII codes below 127 are converted. It is completely equivalent to the UpCase function of the system unit, and is provided for compatiibility only. Errors: None. See also: AnsiLowerCase (331), LowerCase (353), AnsiUpperCase (337) Errors: See also: Program Example87 ; { This program demonstrates the UpperCase f u n c t i o n } Uses s y s u t i l s ; Begin Writeln ( UpperCase ( ' t h i s w i l l come OUT ALL uPpErCaSe ! ' ) ) ; End. 359 Index Abstract, 207 ClearViewPort, 93 Accept, 268, 270 CloseDir, 146 Access, 139 CloseGraph, 93 AddDisk, 36 ClrEol, 23 AddDisk (Linux only), 307 ClrScr, 24 AdjustLineBreaks, 328 CompareMem, 339 allocate ldt descriptors, 64 CompareStr, 339 allocate memory block, 66 CompareText, 340 AnsiCompareStr, 328 Connect, 271, 272 AnsiCompareText, 329 copyfromdos, 66 AnsiExtractQuotedStr, 330 copytodos, 67 AnsiLastChar, 330 create code segment alias descriptor, AnsiLowerCase, 331 67 AnsiQuotedStr, 331 CreateDir, 308 AnsiStrComp, 332 CursorO , 24 AnsiStrIComp, 333 CursorOn, 24 AnsiStrLastChar, 333 AnsiStrLComp, 334 Date, 294 AnsiStrLIComp, 335 DateTimeToFileDate, 295 AnsiStrLower, 336 DateTimeToStr, 295 AnsiStrUpper, 336 DateTimeToString, 295 AnsiUpperCase, 337 DateTimeToSystemTime, 296 AppendStr, 337 DateTimeToTimeStamp, 297 Arc, 92 DateToStr, 297 AssignCrt, 22 DayOfWeek, 298 AssignLst, 265 DecodeDate, 298 AssignPipe, 140 DecodeTime, 299 AssignStr, 338 Delay, 24 AssignStream, 141 DeleteFile, 311 DelLine, 25 Bar, 92 DetectGraph, 93 Bar3D, 92 DirName, 146 BaseName, 142 disable, 67 BCDToInt, 338 DiskFree, 36, 308 BigCursor, 23 DiskSize, 37, 309 Bind, 270, 271 DisposeStr, 207, 341 DoDirSeparators, 311 CFMakeRaw, 143 DosExitCode, 37 CFSetISpeed, 143 dosmemfillchar, 68 CFSetOSpeed, 143 dosmemfillword, 69 ChangeFileExt, 311 dosmemget, 69 Chmod, 144 dosmemmove, 69 Chown, 143 dosmemput, 70 Circle, 92 DosVersion, 38 ClearDevice, 93 DrawPoly, 93 360 INDEX DumpHeap, 111 FileTruncate, 321 Dup, 146 FileWrite, 322 Dup2, 147 FillEllipse, 94 FillPoly, 94 Ellipse, 94 FindClose, 40, 322 Emms, 192 FindFirst, 40, 322 enable, 70 FindNext, 41, 323 EncodeDate, 299 FloatToStr, 341 EncodeTime, 300 FloatToStrF, 342 EnvCount, 38 FloatToText, 344 EnvStr, 39 FLock, 157 EpochToLocal, 148 FloodFill, 94 Exec, 39 FmtStr, 345 Execl, 148 Fork, 161 Execle, 149 Format, 345 Execlp, 150 FormatBuf, 351 Execv, 150 FormatDateTime, 301 Execve, 151 free ldt descriptor, 70 Execvp, 152 free memory block, 71 ExpandFileName, 312 free rm callback, 71 ExpandUNCFileName, 313 FSearch, 41, 159 ExtractFileDir, 313 FSplit, 42 ExtractFileDrive, 313 FSStat, 158 ExtractFileExt, 314 FStat, 159 ExtractFileName, 314 ftok, 119 ExtractFilePath, 314 ExtractRelativePath, 315 get cs, 71 get descriptor access rights, 71 Fcntl, 160 get ds, 72 FD Clr, 153 get linear addr, 72 FD IsSet, 153 get meminfo, 72 FD Set, 154 get next selector increment value, 73 FD ZERO, 153 get page size, 74 fdClose, 154 get pm interrupt, 74 fdFlush, 154 get rm callback, 74 fdOpen, 154 get rm interrupt, 77 fdRead, 155 get run mode, 78 fdSeek, 156 get segment base address, 78 fdTruncate, 156 get segment limit, 79 fdWrite, 157 get ss, 79 FExpand, 39, 157 GetArcCoords, 94 FileAge, 315 GetAspectRatio, 95 FileClose, 316 GetBkColor, 95 FileCreate, 316 GetCBreak, 42 FileDateToDateTime, 300 GetColor, 95 FileExists, 317 GetCurrentDir, 310 FileGetAttr, 317 GetDate, 42, 161 FileGetDate, 318 GetDefaultPalette, 95 FileOpen, 319 GetDirs, 323 FileRead, 319 GetDomainName, 162 FileSearch, 320 GetDriverName, 95 FileSeek, 320 GetEGid, 162 FileSetAttr (Not on Linux), 321 GetEnv, 43, 163 FileSetDate (Not on Linux), 321 GetEpochTime, 163 361 INDEX GetEUid, 163 InitMouse, 197 GetFAttr, 43 inportb, 81 GetFillPattern, 95 inportl, 81 GetFillSettings, 96 inportw, 81 GetFS, 164 InsLine, 26 GetFTime, 44 InstallUserDriver, 100 GetGid, 164 InstallUserFont, 100 GetGraphMode, 96 Intr, 46 GetHostName, 165 IntToHex, 351 GetImage, 96 IntToStr, 352 GetIntVec, 45 IOCtl, 168 GetLastButtonPress, 194 IOperm, 169 GetLastButtonRelease, 195 IsATTY, 169 GetLineSettings, 96 IsLeapYear, 302 GetLongOpts, 51 IsValidIdent, 352 GetMaxColor, 96 GetMaxMode, 96 Keep, 46 GetMaxX, 97 KeyPressed, 27 GetMaxY, 97 Kill, 171 GetModeName, 97 GetModeRange, 97 LeftStr, 353 GetMouseState, 196 Line, 101 Getopt, 51 LineRel, 101 GetPalette, 97 LineTo, 101 GetPaletteSize, 97 Link, 173 GetPeerName, 273 Listen, 274 GetPid, 165 LoadStr, 353 GetPixel, 98 LocalToEpoch, 174 GetPPid, 166 lock code, 82 GetPriority, 166 lock data, 82 GetSocketName, 274 lock linear region, 82 GetSocketOptions, 274 LongDiv, 209 GetTextSettings, 98 LongMul, 209 GetTime, 45, 166 LowerCase, 353 GetUid, 167 LowVideo, 27 GetVerify, 46 LPressed, 198 GetViewSettings, 98 LStat, 172 GetX, 98 GetY, 98 MarkHeap, 111 Glob, 167 MkFifo, 175 global dos alloc, 79 MoveRel, 101 global dos free, 81 MoveTo, 101 GlobFree, 168 MPressed, 198 GotoXY, 25 MSDos, 46 GraphDefaults, 99 MSecsToTimeStamp, 302 GraphErrorMsg, 99 msgctl, 120 GraphResult, 99 msgget, 119 msgrcv, 120 HideMouse, 197 msgsnd, 119 HighVideo, 26 NewStr, 206, 354 ImageSize, 99 Nice, 175 IncMonth, 301 NormVideo, 28 InitGraph, 100 NoSound, 28 362 INDEX Now, 303 set segment base address, 88 set segment limit, 88 OpenDir, 176 SetActivePage, 104 outportb, 83 SetAllPallette, 104 outportl, 83 SetAspectRatio, 104 outportw, 83 SetBkColor, 104 OutText, 102 SetCBreak, 47 OutTextXY, 102 SetColor, 104 SetCurrentDir, 310 PackTime, 47 SetDate, 48 PClose, 177 SetDirSeparators, 324 PieSlice, 102 SetExtraInfo, 112 POpen, 177 SetFAttr, 48 PutImage, 102 SetFillPattern, 105 PutPixel, 102 SetFillStyle, 105 QuotedStr, 354 SetFTime, 48 SetGraphBufSize, 105 ReadDir, 178 SetGraphMode, 105 ReadKey, 28 SetIntVec, 48 realintr, 84 SetLineStyle, 106 Rectangle, 103 SetMouseAscii, 198 Recv, 275 SetMouseHideWindow, 199 RegisterBGIDriver, 103 SetMousePos, 200 RegisterBGIFont, 103 SetMouseShape, 200 RegisterObjects, 207 SetMouseSpeed, 201 RegisterType, 207 SetMouseWindow, 202 RemoveDir, 310 SetMouseXRange, 202 RenameFile, 324 SetMouseYRange, 203 RestoreCRTMode, 103 SetPalette, 106 RightStr, 355 SetPriority, 180 RPressed, 198 SetRGBPalette, 106 SetSocketOptions, 276 S ISBLK, 169 SetTextJustify, 106 S ISCHR, 169 SetTextStyle, 107 S ISDIR, 170 SetTime, 49 S ISFIFO, 170 SetUserCharSize, 107 S ISLNK, 170 SetVerify, 49 S ISREG, 171 SetViewPort, 107 S ISSOCK, 171 SetVisualPage, 108 Sector, 103 SetWriteMode, 108 SeekDir, 178 Shell, 180 seg fillchar, 84 shmat, 129 seg fillword, 85 shmctl, 130 seg move, 86 shmdt, 130 segment to descriptor, 85 shmget, 129 Select, 178 ShowMouse, 203 SelectText, 180 Shutdown, 276 semctl, 124 SigAction, 181 semget, 123 Signal, 183 semop, 123 SigPending, 182 Send, 275 SigProcMask, 182 set descriptor access rights, 86 SigSuspend, 183 set pm interrupt, 86 Sock2File, 276 set rm interrupt, 88 Sock2Text, 277 363 INDEX Socket, 277 TCollection.At, 236 SocketPair, 277 TCollection.AtDelete, 245 Sound, 29 TCollection.AtFree, 244 Str2UnixSockAddr, 277 TCollection.AtInsert, 247 StrAlloc, 279, 326 TCollection.AtPut, 247 StrBufSize, 326 TCollection.Delete, 243 StrCat, 279 TCollection.DeleteAll, 241 StrComp, 280 TCollection.Done, 236 StrCopy, 280 TCollection.Error, 246 StrDispose, 281, 327 TCollection.FirstThat, 239 StrECopy, 281 TCollection.ForEach, 245 StrEnd, 282 TCollection.Free, 242 StrFmt, 355 TCollection.FreeAll, 240 StrIComp, 282 TCollection.FreeItem, 244 StrLCat, 283 TCollection.GetItem, 238 StrLComp, 283 TCollection.IndexOf, 237 StrLCopy, 284 TCollection.Init, 235 StrLen, 284 TCollection.Insert, 243 StrLFmt, 355 TCollection.LastThat, 238 StrLIComp, 285 TCollection.Load, 235 StrLower, 285 TCollection.Pack, 239 StrMove, 286 TCollection.PutItem, 248 StrNew, 286 TCollection.SetLimit, 246 StrPas, 287, 327 TCollection.Store, 248 StrPCopy, 287, 327 TCSendBreak, 187 StrPLCopy, 327 TCSetAttr, 187 StrPos, 288 TCSetPGrp, 187 StrRScan, 288 TDateTime, 294 StrScan, 288 TDosStream.Close, 225 StrToDate, 303 TDosStream.Done, 225 StrToDateTime, 304 TDosStream.Init, 224 StrToInt, 356 TDosStream.Open, 227 StrToIntDef, 357 TDosStream.Read, 227 StrToTime, 305 TDosStream.Seek, 226 StrUpper, 289 TDosStream.Truncate, 225 SwapVectors, 49 TDosStream.Write, 228 SymLink, 184 TellDir, 188 SystemTimeToDateTime, 305 TextBackground, 29 TextColor, 30 tb size, 89 TextHeight, 108 TBufStream.Close, 229 TextWidth, 108 TBufStream.Done, 229 Time, 306 TBufStream.Flush, 230 TimeStampToDateTime, 306 TBufStream.Init, 229 TimeStampToMSecs, 307 TBufStream.Open, 231 TimeToStr, 307 TBufStream.Read, 231 TMemoryStream.Done, 232 TBufStream.Seek, 231 TMemoryStream.Init, 232 TBufStream.Truncate, 230 TMemoryStream.Read, 233 TBufStream.Write, 231 TMemoryStream.Truncate, 233 TCDrain, 185 TMemoryStream.Write, 234 TCFlow, 185 TObject.Done, 215 TCFlush, 185 TObject.Free, 215 TCGetAttr, 186 TObject.Init, 215 TCGetPGrp, 186 transfer bu er, 89 364 INDEX TRect.Assign, 214 TStream.WriteStr, 221 TRect.Contains, 211 TStringCollection.Compare, 254 TRect.Copy, 211 TStringCollection.FreeItem, 255 TRect.Empty, 210 TStringCollection.GetItem, 254 TRect.Equals, 211 TStringCollection.PutItem, 255 TRect.Grow, 214 TStringList.Done, 263 TRect.Intersect, 212 TStringList.Get, 263 TRect.Move, 213 TStringList.Load, 263 TRect.Union, 212 TStrListMaker.Done, 264 TResourceCollection.FreeItem, 259 TStrListMaker.Init, 264 TResourceCollection.GetItem, 259 TStrListMaker.Put, 264 TResourceCollection.KeyOf, 259 TStrListMaker.Store, 264 TResourceCollection.PutItem, 260 TTYName, 187 TResourceFile.Count, 261 TUnSortedStrCollection.Insert, 258 TResourceFile.Delete, 262 TResourceFile.Done, 261 Umask, 188 TResourceFile.Flush, 262 Uname, 188 TResourceFile.Get, 261 UnLink, 188 TResourceFile.Init, 260 unlock code, 89 TResourceFile.KeyAt, 261 unlock data, 89 TResourceFile.Put, 262 unlock linear region, 90 TResourceFile.SwitchTo, 261 UnPackTime, 49 Trim, 357 UpperCase, 359 TrimLeft, 358 Utime, 189 TrimRight, 358 TSortedCollection.Compare, 250 WaitPid, 190 TSortedCollection.IndexOf, 250 WhereX, 30 TSortedCollection.Init, 249 WhereY, 31 TSortedCollection.Insert, 252 Window, 31 TSortedCollection.KeyOf, 250 TSortedCollection.Load, 250 TSortedCollection.Search, 251 TSortedCollection.Store, 253 TStrCollection.Compare, 256 TStrCollection.FreeItem, 257 TStrCollection.GetItem, 256 TStrCollection.PutItem, 257 TStream.Close, 220 TStream.CopyFrom, 223 TStream.Error, 222 TStream.Flush, 220 TStream.Get, 217 TStream.GetPos, 218 TStream.GetSize, 219 TStream.Open, 220 TStream.Put, 221 TStream.Read, 222 TStream.ReadStr, 219 TStream.Reset, 220 TStream.Seek, 222 TStream.StrRead, 217 TStream.StrWrite, 221 TStream.Truncate, 221 TStream.Write, 223 365