Версия для печати темы

Нажмите сюда для просмотра этой темы в обычном формате

Форум «Всё о Паскале» _ Ассемблер _ Файлы и дескрипторы -->> Паскаль

Автор: Altair 20.06.2004 1:06

Как вставить в программу на паскале код открытия, закрытия и т.д. процедур для работы с файлами.
Иначе: мне нужно что-то вроде исходников процедур Assign, reset и т.д.
--------
Что такое дескриптор и можно-ли как то их использовать в пасе?

Автор: BlackShadow 21.06.2004 1:33

В данном случае, дескриптор - это просто 16-битное значение.

Function FileOpen(FileName:PChar):Word;Assembler;
{Возвращает Handle или 0 при ошибке}
Asm
 PUSH DS
 LDS DX,[FileName]
 MOV AX,3D02h {Read+Write}
 INT 21h
 JNC @@1
 XOR AX,AX
@@1:
 POP DS
End;

Function FileCreate(FileName:PChar):Word;Assembler;
{Возвращает Handle или 0 при ошибке}
Asm
 PUSH DS
 LDS DX,[FileName]
 MOV AH,3Ch {Read+Write}
 MOV CX,0020h {Attribute = Archive}
 INT 21h
 JNC @@1
 XOR AX,AX
@@1:
 POP DS
End;

Procedure FileClose(f:Word);Assembler;
Asm
 MOV BX,[f]
 MOV AH,3Eh
 INT 21h
Ebd;

Function FileRead(f:Word;Var Buf;Count:Word):Word;Assembler;
Asm
 PUSH DS
 LDS DX,[Buf]
 MOV CX,[Count]
 MOV BX,[f]
 MOV AH,3Fh
 INT 21h
End;

Function FileWrite(f:Word;Const Buf;Count:Word):Word;Assembler;
Asm
 PUSH DS
 LDS DX,[Buf]
 MOV CX,[Count]
 MOV BX,[f]
 MOV AH,40h
 INT 21h
End;

Ну, это самое простое...

Автор: Dark 21.06.2004 10:10

В общем то BlackShadow прав, но я добавлю еще кое что

FILE OPEN: Function 3Dh

IN:
ah= 3Dh
al= open mode

bits 7-3: нас неинтересует, лучше обнулять
bits 2-0: Access code
000 read only access
001 write only access
010 read and write access

DS:DX= указатель на имя файла в ASCIIZ формате ('test.txt'#0)

Returns:
CF=1 ошибка
AX= error code- don't worry about what they are, if the carry
is set, you didn't open the file.

CF=0 нет ошибок
AX= File Handle ; СОХРАНЯТЬ!!!

---- EXAMPLE ----

    [...]  ;header stuff

   .CODE          ;this stuff is used for all the examples

 FileName  db "TextFile.TXT",0
 FileHandle dw 0
 Buffer    db  300 dup (0)
 BytesRead dw  0
 FileSize  dd  0

   [...]  ;more stuff
   push ds
   mov     ax,3d00h   ; open file for read only
   mov     ax,seg FileName
   mov     ds,ax      ;we use CS, cause it's pointing to the CODE segment
                      ; and our file name is in the code segment
   mov     dx,offset FileName
   int     21h
   jc      FileError_Open

   mov     [FileHandle],ax

   [...]  ;etc...



----------------------------------------------------------------------------
FILE CLOSE: Function 3Eh

IN:
AH= 3Eh
BX= File Handle

RETURN:
CF=1 ошибка

---- EXAMPLE ----

    mov     bx,[FileHandle]
   mov     ah,3eh
   int     21h

----------------------------------------------------------------------------
FILE READ: Function 3Fh

IN:
AH= 3Fh
BX= File Handle
CX= сколько байт читать
DS:DX= куда поместить(FAR адрес памяти)

RETURN:
AX= количество прочитанных байт, если 0 - конец файла

---- EXAMPLE ----

    mov     bx,[FileHandle]
   mov     ax, seg buffer
   mov     ds,ax
   mov     dx,offset buffer
   mov     ah,3Fh
   mov     cx,300
   int     21h

   mov     [BytesRead],ax

----------------------------------------------------------------------------
FILE WRITE: Function 40h

IN:
AH= 40h
BX= File Handle
CX= сколько байт читать
DS:DX= откуда записывать на диск(FAR адрес памяти)

RETURN:
AX= количество записанных байт, если не равно тому что мы помещаем в cx - у нас ошибка

---- EXAMPLE ----

    mov     bx,[FileHandle]
   mov     ax,seg buffer
   mov     ds,ax
   mov     dx,offset buffer
   mov     ah,40h
   mov     cx,[BytesRead]
   int     21h

   cmp     cx,ax
   jne     FileError_Write


----------------------------------------------------------------------------
FILE CREATE: Function 3Ch

IN:
ah= 3Ch
cl= file attribute

bit 0: read-only
bit 1: hidden
bit 2: system
bit 3: volume label
bit 4: sub directory
bit 5: Archive
bit 6&7: reserved

DS:DX= указатель на имя файла в ASCIIZ формате ('test.txt'#0)


Returns:
CF=1 ошибка
AX= код ошибки

CF=0 нет ошибок
AX= File Handle ; СОХРАНЯТЬ!!
---- EXAMPLE ----

    mov     ah,3ch
   mov     ax,seg FileName
   mov     ds,ax      
   mov     dx,offset FileName
   mov     cx,0       ;no attributes
   int     21h
   jc      FileError_Create

   mov     [FileHandle],ax


----------------------------------------------------------------------------
FILE DELETE: Function 41h

IN:
ah= 41h
DS:DX= указатель на имя файла в ASCIIZ формате ('test.txt'#0)

Returns:
CF=1 ОШИБКА!!
AX= error code- 2= file not found, 3= path not found
5= access denied

CF=0 no error

---- EXAMPLE ----

    mov     ah,41h     ;kill the sucker
   mov     ax,seg FileName
   mov     ds,ax
   mov     dx,offset FileName
   int     21h
   jc      FileError_Delete


----------------------------------------------------------------------------
FILE MOVE POINTER: Function 42h

IN:
ah= 42h
BX= File Handle
CX:DX= 32 bit pointer куда переместиться?
AL= 0 offset from beginning of file
= 1 offset from curent position
= 2 offset from the end of the file

Returns:
CF=1 error occured
AX= error code- no move occured

CF=0 no error
DX:AX 32 bit pointer где мы оказались

---- EXAMPLE ----

    mov     ah,42h     ;НАХОЖДЕНИЕ РАЗМЕРА ФАЙЛА!!!
   mov     bx,[FileHandle]
   xor     cx,cx
   xor     dx,dx
   mov     al,2
   int     21h
   
   mov     [word low FileSize],ax
   mov     [word high FileSize],dx;load data into filesize


----------------------------------------------------------------------------
FILE CHANGE MODE: Function 43h

IN:
ah= 43h
DS:DX= указатель на имя файла в ASCIIZ формате ('test.txt'#0)
al= 0
returns file attributes in CX
al= 1
sets file attributes to what's in CX

Returns:
CF=1 error occured
AX= error code- 2= file not found, 3= path not found.
5= access denied

CF=0 no error

---- EXAMPLE ---- Lets erase a hidden file in your root directory...

FileName db "C:\msdos.sys",0

    [...]

   mov     ah,43h         ;change attribute to that of a normal file
   mov     ax,cs
   mov     ds,ax
   mov     dx,offset FileName
   mov     al,1           ;set to whats in CX
   mov     cx,0           ;attribute = 0
   int     21h

   mov     ah,41h         ;Nuke it with the delete command
   int     21h

Автор: Dark 21.06.2004 10:11

ПРОГРАММА НЕ МОЯ =)


;   VERY, VERY simple ANSI/text viewer
;
;   Coded by Draeden [VLA]
;

   DOSSEG
   .MODEL SMALL
   .STACK 200h
   .CODE
   Ideal

;===- Data -===

BufferSeg   dw  0

ErrMsgOpen  db  "Error opening `"
FileName    db  "ANSI.TXT",0,8,"'$"    ;8 is a delete character
                                      ;0 is required for filename
                                      ;(displays a space)
FileLength dw 0

;===- Subroutines -===

PROC DisplayFile NEAR
   push    ds

   mov     ax,cs
   mov     ds,ax
   mov     ax,3d00h   ;open file (ah=3dh)
   mov     dx,offset FileName
   int     21h
   jc      OpenError
   mov     bx,ax      ;move the file handle into bx

   mov     ds,[BufferSeg]
   mov     dx,0           ;load to [BufferSeg]:0000
   mov     ah,3fh
   mov     cx,0FFFFh      ;try to read an entire segments worth
   int     21h

   mov     [cs:FileLength],ax

   mov     ah,3eh
   int     21h            ;close the file

   cld
   mov     si,0
   mov     cx,[cs:FileLength]
PrintLoop:
   mov     ah,2
   lodsb
   mov     dl,al
   int     21h        ;print a character

   dec     cx
   jne     PrintLoop
   
   pop     ds
   ret

OpenError:
   mov     ah,9
   mov     dx,offset ErrMsgOpen
   int     21h

   pop     ds
   ret
ENDP DisplayFile

;===- Main Program -===

START:
   mov     ax,cs
   mov     ds,ax
   mov     bx,ss
   add     bx,200h/10h    ;get past the end of the file
   mov     [BufferSeg],bx ;store the buffer segment

   call    DisplayFile

   mov     ax,4c00h
   int     21h
END START

Автор: Altair 21.06.2004 17:01

Отлично! Спасибо всем!