Дополнительные команды AVR-DOS — различия между версиями

Материал из roboforum.ru Wiki
Перейти к: навигация, поиск
(Новая: '''Список команд DOS''' — нижеследующий список команд для [[операционная си...)
 
м (См. также)
 
(не показаны 93 промежуточные версии этого же участника)
Строка 1: Строка 1:
'''Список команд DOS''' — нижеследующий список [[команда (программирование)|команд]] для [[операционная система|операционной системы]] [[DOS (операционная система)|DOS]]. Начиная с 5-й версии, этот список с кратким описанием каждой команды может быть получен набором команды <code>HELP</code>. Также начиная с 5-й версии справка по конкретной команде может быть получена набором символов '''<code>/?</code>''' после имени команды.  
+
[[Категория:AVR-DOS]]
 +
'''Список команд AVR-DOS''' — список функций библиотеки [[AVR-DOS]].
  
Например, набор команды
+
== Диск/Директория ==
<pre>
+
=== FileDate ===
C:\>ren /?
+
Возвращает дату создания или последнего изменения файла.
</pre>
 
приведёт к получению справки по команде <code>ren</code>:
 
<pre>
 
Переименование одного или нескольких файлов.
 
  
RENAME [диск:][путь]имя_файла1 имя_файла2.
+
<code>sDate = FileDate ()</code>
REN [диск:][путь]имя_файла1 имя_файла2.
 
  
Для конечного файла нельзя указать другой диск или каталог.
+
<code>sDate = FileDate (file)</code>
</pre>
 
  
Все команды DOS являются ''нечувствительными к [[регистр букв|регистру букв]]'', то есть любая команда может быть набрана как строчными, так и заглавными буквами.
+
{| class="wikitable"
 +
| sDate(String)
 +
| Дата создания или изменения(?) файла
 +
|-
 +
| File(String)
 +
| Имя файла в текущей директории<ref name="dosnames">'''8.3''': имя - 8 символов, расширение - 3 символа, разделитель(точка) - 1 символ, всего не более 12 символов</ref><ref name="dirnames">Если не указано, параметром считается последний файл, выбранный с помощью [[Основные команды AVR-DOS#Dir|DIR]]</ref>
 +
|}
  
== Команды ==
+
Пример вызова:
=== attrib ===
 
Вывод и изменение атрибутов файлов.
 
  
ATTRIB <code>[+R | -R] [+A | -A ] [+S | -S] [+H | -H] [диск:] [путь] [имя_файла] [/S] [/D]</code>
+
<source lang="vb"> Print "File demo"
 +
Print Filelen( "josef.img") ; " length" ' length of file
 +
Print Filetime( "josef.img") ; " time" ' time file was changed
 +
Print Filedate( "josef.img") ; " date" ' file date
 +
</source>
  
+  Установка атрибута.
+
=== FileTime ===
-  Снятие атрибута.
+
Возвращает время создания или последнего изменения файла.
R  Атрибут "Только чтение".
 
A  Атрибут "Архивный".
 
S  Атрибут "Системный".
 
H  Атрибут "Скрытый".
 
[диск:] [путь] [имя_файла]
 
    Указание файла или набора файлов для обработки.
 
/S  Обработка файлов с указанными именами в текущей папке
 
    и во всех ее подпапках.
 
/D  Обработка и файлов, и папок.
 
  
Эквивалентна команде Unix [[chmod]].
+
<code>sTime = FileTime ()</code>
  
=== cd or chdir ===
+
<code>sTime = FileTime (file)</code>
Вывод имени либо смена текущего каталога.
 
  
CHDIR <code>[/D] [диск:][путь]</code>
+
{| class="wikitable"
CHDIR <code>[..]</code>
+
| sTime(String)
CD <code>[/D] [диск:][путь]</code>
+
| Время создания или изменения(?) файла
CD <code>[..]</code>
+
|-
 +
| File(String)
 +
| Имя файла в текущей директории<ref name="dosnames">'''8.3''': имя - 8 символов, расширение - 3 символа, разделитель(точка) - 1 символ, всего не более 12 символов</ref><ref name="dirnames">Если не указано, параметром считается последний файл, выбранный с помощью [[Основные команды AVR-DOS#Dir|DIR]]</ref>
 +
|}
  
  ..  обозначает переход в родительский каталог.
+
Пример вызова:
  
Команда CD диск: отображает имя текущего каталога указанного диска.
+
<source lang="vb"> Print "File demo"
Команда CD без параметров отображает имена текущих диска и каталога.
+
Print Filelen( "josef.img") ; " length" ' length of file
 +
Print Filetime( "josef.img") ; " time" ' time file was changed
 +
Print Filedate( "josef.img") ; " date" ' file date
 +
</source>
  
Параметр /D используется для одновременной смены
+
== Файлы ==
текущих диска и каталога.
+
=== Flush ===
 +
Скидывает кеш текущего файла на диск и обновляет информацию раздела, директории.
  
Изменение команды CHDIR при включении расширенной обработки команд:
+
Процедура осуществляет запись всей несохраненной информации о/в файле на диск. Обычно запись на диск производится при закрытии файлового потока или переходе на другой сектор файла, однако вы можете поменять параметр [[Окружение AVR-DOS#Конфигурация файловой системы|cFATDirSaveAtEnd]], в этом случае вам придется принудительно сбрасывать изменения файла на диск.
  
Имя текущего каталога в строке вызова преобразуется к тому же регистру
+
<code>Flush #bFileNumber</code>
символов, что и для существующих имен на диске.  Так, команда CD C:\TEMP
 
на самом деле сделает текущим каталог C:\Temp, если он существует на диске.
 
  
Команда CHDIR перестает рассматривать пробелы как разделители, что позволяет
+
<code>Flush</code>
перейти в подкаталог, имя которого содержит пробелы, не заключая все имя
 
каталога в кавычки.  Например:
 
  
    chdir \winnt\profiles\username\programs\start menu
+
{| class="wikitable"
 +
| BFileNumber(Byte)
 +
| Идентификационный номер открытого файлового потока<ref name="identnumber">Принадлежит целому множеству 0..255, может быть переменной или константой. Используйте числа 1..127 для пользовательских идентификаторов. Для получения свободного идентификатора используйте функцию [[Основные команды AVR-DOS#FreeFile|FreeFile]](возвращает 128..255)</ref>. Если не указан, то изменения всех открытых файлов сбрасываются на диск.
 +
|}
  
приводит к тому же результату, что и:
+
Пример вызова:
  
    cd "\winnt\profiles\username\programs\start menu"
+
<source lang="vb"> $include "startup.inc"
  
При отключении расширенной обработки команд используется только второй вариант.
+
'open the file in BINARY mode
:Эквивалентна команде Unix <code>cd</code> (с параметрами), или <code>pwd</code> (без параметров).
+
Open "test.biN" For Binary As #2
 +
Put #2 , B ' write a byte
 +
Put #2 , W ' write a word
 +
Put #2 , L ' write a long
 +
Ltemp = Loc(#2) + 1 ' get the position of the next byte
 +
Print Ltemp ; " LOC" ' store the location of the file pointer
 +
Print Lof(#2) ; " length of file"
 +
Print Fileattr(#2) ; " file mode" ' should be 32 for binary
 +
Put #2 , Sn ' write a single
 +
Put #2 , Stxt ' write a string
  
=== chkdsk ===
+
Flush #2 ' flush to disk
Проверка диска и вывод отчета.
+
Close #2
 +
</source>
  
 +
=== Get ===
 +
Reads a byte from the hardware or software UART. Reads data from a file opened in BINARY mode.
  
CHKDSK <code>[том:[[путь]имя_файла]] [/F] [/V] [/R] [/X] [/I]  [/C] [/L[:размер]]</code>
+
GET in combination with the software/hardware UART is provided for compatibility with BASCOM-8051. It reads one byte.
 +
GET in combination with the AVR-DOS filesystem is very flexible and versatile. It works on files opened in BINARY mode and you can reads all data types.
 +
By default you only need to provide the variable name. When the variable is a byte, 1 byte wil be read. When the variable is a word or integer, 2 bytes will be read. When the variable is a long or single, 4 bytes will be read. When the variable is a string, the number of bytes that will be read is equal to the dimensioned size of the string. DIM S as string * 10 , would read 10 bytes.
 +
Note that when you specify the length for a string, the maximum length is 255. The maximum length for a non-string array is 65535.
 +
<source lang="vb"> Example :  
 +
GET #1 , var ,,2 ‘ read 2 bytes, start at current position
 +
GET #1, var , PS ‘ start at position stored in long PS
 +
GET #1, var , PS, 2 ‘ start at position stored in long PS and read 2 bytes</source>
  
 +
<code>GET #channel, var</code>
  
  Том          Определяет точку подключения, имя тома или букву проверяемого диска
+
<code>GET #channel, var , [pos] [, length]</code>
              с двоеточием.
 
  имя_файла    Файлы, проверяемые на наличие фрагментации (только  FAT/FAT32).
 
  /F            Исправление ошибок на диске.
 
  /V            Для FAT/FAT32: вывод полного пути и имени для каждого файла
 
                на этом диске.
 
                Для NTFS: также вывод сообщений об очистке.
 
  /R            Поиск поврежденных секторов и восстановление их содержимого.
 
                (требует /F).
 
  /L:размер    Только для NTFS: изменение размера файла журнала до указанной
 
                величины (в КБ). Если размер не указан, выводится текущее
 
                значение размера.
 
  /X            При необходимости предварительное отключение
 
                тома. Все открытые дескрипторы для этого тома будут
 
                недействительны. (требует /F).
 
  /I            Только для NTFS: менее строгая проверка индексных элементов.
 
  /C            Только для NTFS: пропуск проверки циклов внутри структуры папок.
 
  
 +
{| class="wikitable"
 +
| #channel(...)
 +
| A channel number, which identifies an opened file. This can be a hard coded constant or a variable
 +
|-
 +
| Var(...)
 +
| The variable or variable array that will be assigned with the data from the file
 +
|-
 +
| Pos(...)
 +
| This is an optional parameter that may be used to specify the postion where the reading must start from. This must be a long variable
 +
|-
 +
| Length(...)
 +
| This is an optional parameter that may be used to specify how many bytes must be read from the file.
 +
|}
  
Ключи /I или /C укорачивают время выполнения CHKDSK за счет пропуска некоторых
+
Пример вызова:
проверок тома.
 
:Эквивалентна команде <code>fsck</code> в Unix.
 
  
=== cls ===
+
<source lang="vb"> 'for the binary file demo we need some variables of different types
:Очищает экран.
+
Dim B As Byte , W As Word , L As Long , Sn As Single , Ltemp As Long
 +
Dim Stxt As String * 10
 +
B = 1 : W = 50000 : L = 12345678 : Sn = 123.45 : Stxt = "test"
  
cls
+
'open the file in BINARY mode
:Эквивалентна команде <code>clear</code> в Unix.
+
Open "test.biN" For Binary As #2
 +
Put #2 , B ' write a byte
 +
Put #2 , W ' write a word
 +
Put #2 , L ' write a long
 +
Ltemp = Loc(#2) + 1 ' get the position of the next byte
 +
Print Ltemp ; " LOC" ' store the location of the file pointer
 +
Print Seek(#2) ; " = LOC+1"
  
=== del, erase ===
+
Print Lof(#2) ; " length of file"
Удаление одного или нескольких файлов.
+
Print Fileattr(#2) ; " file mode" ' should be 32 for binary
 +
Put #2 , Sn ' write a single
 +
Put #2 , Stxt ' write a string
  
DEL <code>[/P] [/F] [/S] [/Q] [/A[[:]атрибуты]] имена</code>
+
Flush #2 ' flush to disk
ERASE <code>[/P] [/F] [/S] [/Q] [/A[[:]атрибуты]] имена</code>
+
Close #2
  
  имена              Имена одного или нескольких файлов. Для удаления сразу
+
'now open the file again and write only the single
              нескольких файлов используются подстановочные знаки.
+
Open "test.bin" For Binary As #2
              Если указан каталог, из него будут удалены все файлы.
+
L = 1 'specify the file position
 +
B = Seek(#2 , L) ' reset is the same as using SEEK #2,L
 +
Get #2 , B ' get the byte
 +
Get #2 , W ' get the word
 +
Get #2 , L ' get the long
 +
Get #2 , Sn ' get the single
 +
Get #2 , Stxt ' get the string
 +
Close #2
 +
</source>
  
  /P          Запрос на подтверждение перед удалением каждого файла.
+
=== Put ===
  /F          Принудительное удаление файлов, доступных только для чтения.
+
Writes a byte to the hardware or software UART. Writes data to a file opened in BINARY mode.
  /S          Удаление указанных файлов из всех подкаталогов.
 
  /Q          Отключение запроса на подтверждение при удалении файлов.
 
  /A          Отбор файлов для удаления по атрибутам.
 
  атрибуты    S  Системные файлы      R  Доступные только для чтения
 
              H  Скрытые файлы        A  Файлы для архивирования
 
              Префикс "-" имеет значение НЕ
 
  
Изменение команд DEL и ERASE при включении расширенной обработки команд:
+
PUT in combination with the software/hardware UART is provided for compatibility with BASCOM-8051. It writes one byte
 +
PUT in combination with the AVR-DOS filesystem is very flexible and versatile. It works on files opened in BINARY mode and you can write all data types.
 +
By default you only need to provide the variable name. When the variable is a byte, 1 byte wil be written. When the variable is a word or integer, 2 bytes will be written. When the variable is a long or single, 4 bytes will be written. When the variable is a string, the number of bytes that will be written is equal to the dimensioned size of the string. DIM S as string * 10 , would write 10 bytes.
 +
Note that when you specify the length for a string, the maximum length is 255. The maximum length for a non-string array is 65535.
 +
Example:
 +
<source lang="vb"> PUT #1, var
 +
PUT #1, var , , 2 ‘ write 2 bytes at default position
 +
PUT #1, var ,PS, 2 ‘ write 2 bytes at location storied in variable PS</source>
  
Результаты вывода для ключа /S принимают обратный характер, то есть выводятся
+
<code>PUT #channel, var</code>
только имена удаленных файлов, а не файлов, которые не удалось найти.
 
:Эквивалентна команде <code>rm</code> в Unix..
 
  
=== deltree ===
+
<code>PUT #channel, var ,[pos] [,length]</code>
:Удаление директории вместе с файлами и другими директориями, которые она включает.
 
  
deltree <code>[/y] ''директория''</code>
+
{| class="wikitable"
 +
| #channel(...)
 +
| A channel number, which identifies an opened file. This can be a hard coded constant or a variable.
 +
|-
 +
| Var(...)
 +
| The variable or variable array that will be written to the file
 +
|-
 +
| Pos(...)
 +
| This is an optional parameter that may be used to specify the postion where the data must be written to. This must be a long variable.
 +
|-
 +
| Length(...)
 +
| This is an optional parameter that may be used to specify how many bytes must be written to the file.
 +
|}
  
В Unix, функциональность <code>deltree</code> предоставляется командой <code>rm</code> с параметром <code>-r</code>.
+
Пример вызова:
  
=== dir ===
+
<source lang="vb"> 'for the binary file demo we need some variables of different types
Вывод списка файлов и подкаталогов из указанного каталога.
+
Dim B As Byte , W As Word , L As Long , Sn As Single , Ltemp As Long
 +
Dim Stxt As String * 10
 +
B = 1 : W = 50000 : L = 12345678 : Sn = 123.45 : Stxt = "test"
  
DIR <code>[диск:][путь][имя_файла] [/A[[:]атрибуты]] [/B] [/C] [/D] [/L] [/N]</code>
+
'open the file in BINARY mode
<code>[/O[[:]порядок]] [/P] [/Q] [/S] [/T[[:]время]] [/W] [/X] [/4]</code>
+
Open "test.biN" For Binary As #2
 +
Put #2 , B ' write a byte
 +
Put #2 , W ' write a word
 +
Put #2 , L ' write a long
 +
Ltemp = Loc(#2) + 1 ' get the position of the next byte
 +
Print Ltemp ; " LOC" ' store the location of the file pointer
 +
Print Seek(#2) ; " = LOC+1"
  
  [диск:][путь][имя_файла]
+
Print Lof(#2) ; " length of file"
            Диск, каталог и/или файлы, которые следует включить в список.
+
Print Fileattr(#2) ; " file mode" ' should be 32 for binary
 +
Put #2 , Sn ' write a single
 +
Put #2 , Stxt ' write a string
  
  /A        Вывод файлов с указанными атрибутами.
+
Flush #2 ' flush to disk
  атрибуты  D  Каталоги                    R  Доступные только для чтения
+
Close #2
            H  Скрытые файлы              A  Файлы для архивирования
 
            S  Системные файлы            Префикс "-" имеет значение НЕ
 
  /B        Вывод только имен файлов.
 
  /C        Применение разделителя групп разрядов для вывода размеров файлов
 
            (по умолчанию).  Для отключения этого режима служит ключ /-C.
 
  /D        Вывод списка в несколько столбцов с сортировкой по столбцам.
 
  /L        Использование нижнего регистра для имен файлов.
 
  /N        Отображение имен файлов в крайнем правом столбце.
 
  /O        Сортировка списка отображаемых файлов.
 
  порядок    N  По имени (алфавитная)      S  По размеру (сперва меньшие)
 
            E  По расширению (алфавитная)  D  По дате (сперва более старые)
 
            G  Начать список с каталогов  Префикс "-" обращает порядок
 
  /P        Пауза после заполнения каждого экрана.
 
  /Q        Вывод сведений о владельце файла.
 
  /S        Вывод списка файлов из указанного каталога и его подкаталогов.
 
  /T        Выбор поля времени для отображения и сортировки
 
  время      C  Создание
 
            A  Последнее использование
 
            W  Последнее изменение
 
  /W        Вывод списка в несколько столбцов.
 
  /X        Отображение коротких имен для файлов, чьи имена не соответствуют
 
            стандарту 8.3. Формат аналогичен выводу с ключом /N, но короткие
 
            имена файлов выводятся слева от длинных. Если короткого имени у
 
            файла нет, вместо него выводятся пробелы.
 
  /4        Вывод номера года в четырехзначном формате
 
  
Стандартный набор ключей можно записать в переменную среды DIRCMD. Для отмены
+
'now open the file again and write only the single
их действия введите в команде те же ключи с префиксом "-", например: /-W.
+
Open "test.bin" For Binary As #2
:Эквивалентна команде <code>ls</code> в unix.
+
L = 1 'specify the file position
 +
B = Seek(#2 , L) ' reset is the same as using SEEK #2,L
 +
Get #2 , B ' get the byte
 +
Get #2 , W ' get the word
 +
Get #2 , L ' get the long
 +
Get #2 , Sn ' get the single
 +
Get #2 , Stxt ' get the string
 +
Close #2
 +
</source>
  
=== format ===
+
=== Seek ===
Форматирование диска.
+
Function: Returns the position of the next Byte to be read or written.
 +
Statement: Sets the position of the next Byte to be read or written.
  
FORMAT <code>том: [/FS:система] [/V:метка] [/Q] [/A:размер] [/C] [/X]</code>
+
This function returns the position of the next Byte to be read or written. If an error occures, 0 is returned. Check DOS-Error in variable gbDOSError<ref name="OkrDOS">[[Окружение AVR-DOS#Коды ошибок|Коды ошибок]]</ref>..
 +
The statetement also returns an error in the gbDOSerror variable in the event that an error occurs.
 +
You can for example not set the fileposition behinds the filesize.
 +
In QB/VB the file is filled with 0 bytes when you set the filepointer behind the size of the file. For embedded systems this does not seem a good idea.
 +
Seek and Loc seems to do the same function, but take care : the seek function will return the position of the next read/write, while the Loc function returns the position of the last read/write. You may say that Seek = Loc+1.
 +
'''Difference with QB'''
 +
In QB/VB you can use seek to make the file bigger. When a file is 100 bytes long, setting the filepointer to 200 will increase the file with 0 bytes. By design this is not the case in AVR-DOS.
  
FORMAT <code>том: [/V:метка] [/Q] [/F:размер]</code>
+
<code>Function: NextReadWrite = Seek (#bFileNumber)
  
FORMAT <code>тома: [/V:метка] [/Q] [/T:дорожки /N:секторы]</code>
+
Statement: Seek #bFileNumber, NewPos)</code>
  
FORMAT <code>тома: [/V:метка] [/Q]</code>
+
{| class="wikitable"
 +
| bFileNumber(Byte)
 +
| Filenumber, which identifies an opened file
 +
|-
 +
| NextReadWrite(Long)
 +
| A Long Variable, which is assigned with the Position of the next Byte to be read or written (1-based)
 +
|-
 +
| NewPos(Long)
 +
| A Long variable that holds the new position the filepointer must be set too.
 +
|}
  
FORMAT <code>том [/Q]</code>
+
Пример вызова:
  
  том            Указывает букву диска (с последующим двоеточием),
+
<source lang="vb"> Open "test.biN" For Binary As #2
                  точку подключения или имя тома.
+
Put #2 , B ' write a byte
  /FS:filesystem  Указывает тип файловой системы (FAT, FAT32 или NTFS).
+
Put #2 , W ' write a word
  /V:метка        Метка тома.
+
Put #2 , L ' write a long
  /Q              Быстрое форматирование.
+
Ltemp = Loc(#2) + 1 ' get the position of the next byte
  /C              Только для NTFS: Установка режима сжатия по умолчанию для
+
Print Ltemp ; " LOC" ' store the location of the file pointer
                  всех файлов, создаваемых на новом томе.
+
Print Seek(#2) ; " = LOC+1"
  /X              Инициирует отключение тома, в качестве первого действия, если
 
                это необходимо. Все открытые дескрипторы тома будут неверны.
 
  /A:размер        Заменяет размер кластера по умолчанию. В общих случаях
 
                  рекомендуется использовать размеры кластера по умолчанию.
 
                  NTFS поддерживает размеры 512, 1024, 2048, 4096, 8192, 16КБ,
 
                  32КБ, 64K.
 
                  FAT поддерживает размеры 512, 1024, 2048, 4096, 8192, 16КБ,
 
                  32КБ, 64КБ, (128КБ, 256КБ для размера сектора > 512 Байт).
 
                  FAT32 поддерживает размеры 512, 1024, 2048, 4096, 8192, 16КБ,
 
                  32КБ, 64КБ, (128КБ, 256КБ для размера сектора > 512 Байт).
 
  
                  Файловые системы FAT и FAT32 налагают следующие ограничения
+
Close #2
                  на число кластеров тома:
 
  
                  FAT: число кластеров <= 65526
+
'now open the file again and write only the single
                  FAT32: 65526 < число кластеров < 4177918
+
Open "test.bin" For Binary As #2
 +
Seek #2 , Ltemp ' set the filepointer
 +
Sn = 1.23 ' change the single value so we can check it better
 +
Put #2 , Sn = 1 'specify the file position
 +
Close #2
 +
</source>
  
                  Выполнение команды Format будет немедленно прервано, если
+
== Свойства файла ==
                  будет обнаружено нарушение указанных выше ограничений,
+
=== LOC ===
                  используя указанный размер кластеров.
+
Returns the position of last read or written Byte of the file.
  
                  Сжатие томов NTFS не поддерживается для размеров кластеров
+
This function returns the position of the last read or written Byte. If an error occurs, 0 is returned. Check DOS-Error in variable gbDOSError<ref name="OkrDOS">[[Окружение AVR-DOS#Коды ошибок|Коды ошибок]]</ref>.. If the file position pointer is changed with the command SEEK, this function can not be used till the next read/write operation.
                  более 4096 Байт.
+
'''Difference with QB'''
 +
This function differs from QB. In QB the byte position is divided by 128.
  
  /F:размер      Указывает размер форматируемых гибких дисков (1,44)
+
<code>lLastReadWritten = Loc (#bFileNumber)</code>
  /T:дорожки      Число дорожек на каждой стороне диска.
 
  /N:секторы      Число секторов на каждой дорожке.
 
  
== См. также ==
+
{| class="wikitable"
* [[Запускаем AVR-DOS на SD-Card МиниБота]]
+
| bFileNumber(Byte)
 +
| Filenumber, which identifies an opened file
 +
|-
 +
| lLastReadWritten(Long)
 +
| Variable, whichsigned with the Position of last read or written Byte (1-based)
 +
|}
 +
 
 +
Пример вызова:
 +
 
 +
<source lang="vb"> 'open the file in BINARY mode
 +
Open "test.biN" For Binary As #2
 +
Put #2 , B ' write a byte
 +
Put #2 , W ' write a word
 +
Put #2 , L ' write a long
 +
Ltemp = Loc(#2) + 1 ' get the position of the next byte
 +
Print Ltemp ; " LOC" ' store the location of the file pointer
 +
Print Lof(#2) ; " length of file"
 +
Print Fileattr(#2) ; " file mode" ' should be 32 for binary
 +
Put #2 , Sn ' write a single
 +
Put #2 , Stxt ' write a string
 +
 
 +
Flush #2 ' flush to disk
 +
Close #2
 +
</source>
 +
 
 +
=== FileAttr ===
 +
Возвращает [[Окружение AVR-DOS#Использование команд ввода-вывода в различных режимах|режим открытия]] файлового потока.
 +
 
 +
<code>bFileAttribut = FileAttr (bFileNumber)</code>
 +
 
 +
{| class="wikitable"
 +
| bFileAttribut(Long)
 +
| Режим:
 +
'''1''' - INPUT<br/>
 +
'''2''' - OUTPUT<br/>
 +
'''8''' - APPEND<br/>
 +
'''32''' - BINARY
 +
|-
 +
| bFileNumber(Byte)
 +
| Идентификационный номер открытого файлового потока<ref name="identnumber">Принадлежит целому множеству 0..255, может быть переменной или константой. Используйте числа 1..127 для пользовательских идентификаторов. Для получения свободного идентификатора используйте функцию [[#FreeFile|FreeFile]](возвращает 128..255)</ref>
 +
|}
 +
 
 +
Пример вызова:
 +
 
 +
<source lang="vb"> 'open the file in BINARY mode
 +
Open "test.biN" For Binary As #2
 +
Print Fileattr(#2) ; " file mode" ' should be 32 for binary
 +
Put #2 , Sn ' write a single
 +
Put #2 , Stxt ' write a string
 +
Close #2
 +
</source>
 +
 
 +
== Другие ==
 +
=== Bload ===
 +
Writes the Content of a File into SRAM.
 +
 
 +
This function writes the content of a file to a desired space in SRAM. A free handle is needed for this function.
 +
 
 +
<code>BLoad sFileName, wSRAMPointer</code>
 +
 
 +
{| class="wikitable"
 +
| sFileName(Long)
 +
| Name of the File to be read
 +
|-
 +
| wSRAMPointer(Word)
 +
| Variable, which holds the SRAM Address to which the content of the file should be written
 +
|}
 +
 
 +
Пример вызова:
 +
 
 +
<source lang="vb"> 'now the good old bsave and bload
 +
Dim Ar(100) As Byte , I As Byte
 +
For I = 1 To 100
 +
Ar(i) = I ' fill the array
 +
Next
 +
 
 +
Wait 2
 +
 
 +
W = Varptr(ar(1))
 +
Bsave "josef.img" , W , 100
 +
For I = 1 To 100
 +
Ar(i) = 0 ' reset the array
 +
Next
 +
 
 +
Bload "josef.img" , W ' Josef you are amazing !
 +
 
 +
For I = 1 To 10
 +
Print Ar(i) ; " " ;
 +
Next
 +
Print
 +
</source>
 +
 
 +
=== Bsave ===
 +
Save a range in SRAM to a Fileю
 +
 
 +
This function writes a range from the SRAM to a file. A free file handle is needed for this function.
 +
 
 +
<code>BSave sFileName, wSRAMPointer, wLength</code>
 +
 
 +
{| class="wikitable"
 +
| sFileName(Long)
 +
| Name of the File to be written
 +
|-
 +
| wSRAMPointer(Word)
 +
| Variable, which holds the SRAM Address, from where SRAM should be written to a File
 +
|-
 +
| wLength(Word)
 +
| Count of Bytes from SRAM, which should be written to the file
 +
|}
 +
 
 +
Пример вызова:
 +
 
 +
<source lang="vb">'now the good old bsave and bload
 +
Dim Ar(100) As Byte , I As Byte
 +
For I = 1 To 100
 +
Ar(i) = I ' fill the array
 +
Next
 +
 
 +
Wait 2
 +
 
 +
W = Varptr(ar(1))
 +
Bsave "josef.img" , W , 100
 +
For I = 1 To 100
 +
Ar(i) = 0 ' reset the array
 +
Next
 +
 
 +
Bload "josef.img" , W ' Josef you are amazing !
  
 +
For I = 1 To 10
 +
Print Ar(i) ; " " ;
 +
Next
 +
Print
 +
</source>
  
{{compu-soft-stub}}
+
== Сноски ==
 +
<references />
  
[[Категория:МиниБот]]
+
== См. также ==
 +
* [[AVR-DOS]]
 +
* [[Основные команды AVR-DOS]]

Текущая версия на 08:29, 9 января 2009

Список команд AVR-DOS — список функций библиотеки AVR-DOS.

Диск/Директория

FileDate

Возвращает дату создания или последнего изменения файла.

sDate = FileDate ()

sDate = FileDate (file)

sDate(String) Дата создания или изменения(?) файла
File(String) Имя файла в текущей директории[1][2]

Пример вызова:

<source lang="vb"> Print "File demo" Print Filelen( "josef.img") ; " length" ' length of file Print Filetime( "josef.img") ; " time" ' time file was changed Print Filedate( "josef.img") ; " date" ' file date </source>

FileTime

Возвращает время создания или последнего изменения файла.

sTime = FileTime ()

sTime = FileTime (file)

sTime(String) Время создания или изменения(?) файла
File(String) Имя файла в текущей директории[1][2]

Пример вызова:

<source lang="vb"> Print "File demo" Print Filelen( "josef.img") ; " length" ' length of file Print Filetime( "josef.img") ; " time" ' time file was changed Print Filedate( "josef.img") ; " date" ' file date </source>

Файлы

Flush

Скидывает кеш текущего файла на диск и обновляет информацию раздела, директории.

Процедура осуществляет запись всей несохраненной информации о/в файле на диск. Обычно запись на диск производится при закрытии файлового потока или переходе на другой сектор файла, однако вы можете поменять параметр cFATDirSaveAtEnd, в этом случае вам придется принудительно сбрасывать изменения файла на диск.

Flush #bFileNumber

Flush

BFileNumber(Byte) Идентификационный номер открытого файлового потока[3]. Если не указан, то изменения всех открытых файлов сбрасываются на диск.

Пример вызова:

<source lang="vb"> $include "startup.inc"

'open the file in BINARY mode Open "test.biN" For Binary As #2 Put #2 , B ' write a byte Put #2 , W ' write a word Put #2 , L ' write a long Ltemp = Loc(#2) + 1 ' get the position of the next byte Print Ltemp ; " LOC" ' store the location of the file pointer Print Lof(#2) ; " length of file" Print Fileattr(#2) ; " file mode" ' should be 32 for binary Put #2 , Sn ' write a single Put #2 , Stxt ' write a string

Flush #2 ' flush to disk Close #2 </source>

Get

Reads a byte from the hardware or software UART. Reads data from a file opened in BINARY mode.

GET in combination with the software/hardware UART is provided for compatibility with BASCOM-8051. It reads one byte. GET in combination with the AVR-DOS filesystem is very flexible and versatile. It works on files opened in BINARY mode and you can reads all data types. By default you only need to provide the variable name. When the variable is a byte, 1 byte wil be read. When the variable is a word or integer, 2 bytes will be read. When the variable is a long or single, 4 bytes will be read. When the variable is a string, the number of bytes that will be read is equal to the dimensioned size of the string. DIM S as string * 10 , would read 10 bytes. Note that when you specify the length for a string, the maximum length is 255. The maximum length for a non-string array is 65535. <source lang="vb"> Example : GET #1 , var ,,2 ‘ read 2 bytes, start at current position GET #1, var , PS ‘ start at position stored in long PS GET #1, var , PS, 2 ‘ start at position stored in long PS and read 2 bytes</source>

GET #channel, var

GET #channel, var , [pos] [, length]

#channel(...) A channel number, which identifies an opened file. This can be a hard coded constant or a variable
Var(...) The variable or variable array that will be assigned with the data from the file
Pos(...) This is an optional parameter that may be used to specify the postion where the reading must start from. This must be a long variable
Length(...) This is an optional parameter that may be used to specify how many bytes must be read from the file.

Пример вызова:

<source lang="vb"> 'for the binary file demo we need some variables of different types Dim B As Byte , W As Word , L As Long , Sn As Single , Ltemp As Long Dim Stxt As String * 10 B = 1 : W = 50000 : L = 12345678 : Sn = 123.45 : Stxt = "test"

'open the file in BINARY mode Open "test.biN" For Binary As #2 Put #2 , B ' write a byte Put #2 , W ' write a word Put #2 , L ' write a long Ltemp = Loc(#2) + 1 ' get the position of the next byte Print Ltemp ; " LOC" ' store the location of the file pointer Print Seek(#2) ; " = LOC+1"

Print Lof(#2) ; " length of file" Print Fileattr(#2) ; " file mode" ' should be 32 for binary Put #2 , Sn ' write a single Put #2 , Stxt ' write a string

Flush #2 ' flush to disk Close #2

'now open the file again and write only the single Open "test.bin" For Binary As #2 L = 1 'specify the file position B = Seek(#2 , L) ' reset is the same as using SEEK #2,L Get #2 , B ' get the byte Get #2 , W ' get the word Get #2 , L ' get the long Get #2 , Sn ' get the single Get #2 , Stxt ' get the string Close #2 </source>

Put

Writes a byte to the hardware or software UART. Writes data to a file opened in BINARY mode.

PUT in combination with the software/hardware UART is provided for compatibility with BASCOM-8051. It writes one byte PUT in combination with the AVR-DOS filesystem is very flexible and versatile. It works on files opened in BINARY mode and you can write all data types. By default you only need to provide the variable name. When the variable is a byte, 1 byte wil be written. When the variable is a word or integer, 2 bytes will be written. When the variable is a long or single, 4 bytes will be written. When the variable is a string, the number of bytes that will be written is equal to the dimensioned size of the string. DIM S as string * 10 , would write 10 bytes. Note that when you specify the length for a string, the maximum length is 255. The maximum length for a non-string array is 65535. Example: <source lang="vb"> PUT #1, var PUT #1, var , , 2 ‘ write 2 bytes at default position PUT #1, var ,PS, 2 ‘ write 2 bytes at location storied in variable PS</source>

PUT #channel, var

PUT #channel, var ,[pos] [,length]

#channel(...) A channel number, which identifies an opened file. This can be a hard coded constant or a variable.
Var(...) The variable or variable array that will be written to the file
Pos(...) This is an optional parameter that may be used to specify the postion where the data must be written to. This must be a long variable.
Length(...) This is an optional parameter that may be used to specify how many bytes must be written to the file.

Пример вызова:

<source lang="vb"> 'for the binary file demo we need some variables of different types Dim B As Byte , W As Word , L As Long , Sn As Single , Ltemp As Long Dim Stxt As String * 10 B = 1 : W = 50000 : L = 12345678 : Sn = 123.45 : Stxt = "test"

'open the file in BINARY mode Open "test.biN" For Binary As #2 Put #2 , B ' write a byte Put #2 , W ' write a word Put #2 , L ' write a long Ltemp = Loc(#2) + 1 ' get the position of the next byte Print Ltemp ; " LOC" ' store the location of the file pointer Print Seek(#2) ; " = LOC+1"

Print Lof(#2) ; " length of file" Print Fileattr(#2) ; " file mode" ' should be 32 for binary Put #2 , Sn ' write a single Put #2 , Stxt ' write a string

Flush #2 ' flush to disk Close #2

'now open the file again and write only the single Open "test.bin" For Binary As #2 L = 1 'specify the file position B = Seek(#2 , L) ' reset is the same as using SEEK #2,L Get #2 , B ' get the byte Get #2 , W ' get the word Get #2 , L ' get the long Get #2 , Sn ' get the single Get #2 , Stxt ' get the string Close #2 </source>

Seek

Function: Returns the position of the next Byte to be read or written. Statement: Sets the position of the next Byte to be read or written.

This function returns the position of the next Byte to be read or written. If an error occures, 0 is returned. Check DOS-Error in variable gbDOSError[4].. The statetement also returns an error in the gbDOSerror variable in the event that an error occurs. You can for example not set the fileposition behinds the filesize. In QB/VB the file is filled with 0 bytes when you set the filepointer behind the size of the file. For embedded systems this does not seem a good idea. Seek and Loc seems to do the same function, but take care : the seek function will return the position of the next read/write, while the Loc function returns the position of the last read/write. You may say that Seek = Loc+1. Difference with QB In QB/VB you can use seek to make the file bigger. When a file is 100 bytes long, setting the filepointer to 200 will increase the file with 0 bytes. By design this is not the case in AVR-DOS.

Function: NextReadWrite = Seek (#bFileNumber)

Statement: Seek #bFileNumber, NewPos)

bFileNumber(Byte) Filenumber, which identifies an opened file
NextReadWrite(Long) A Long Variable, which is assigned with the Position of the next Byte to be read or written (1-based)
NewPos(Long) A Long variable that holds the new position the filepointer must be set too.

Пример вызова:

<source lang="vb"> Open "test.biN" For Binary As #2 Put #2 , B ' write a byte Put #2 , W ' write a word Put #2 , L ' write a long Ltemp = Loc(#2) + 1 ' get the position of the next byte Print Ltemp ; " LOC" ' store the location of the file pointer Print Seek(#2) ; " = LOC+1"

Close #2

'now open the file again and write only the single Open "test.bin" For Binary As #2 Seek #2 , Ltemp ' set the filepointer Sn = 1.23 ' change the single value so we can check it better Put #2 , Sn = 1 'specify the file position Close #2 </source>

Свойства файла

LOC

Returns the position of last read or written Byte of the file.

This function returns the position of the last read or written Byte. If an error occurs, 0 is returned. Check DOS-Error in variable gbDOSError[4].. If the file position pointer is changed with the command SEEK, this function can not be used till the next read/write operation. Difference with QB This function differs from QB. In QB the byte position is divided by 128.

lLastReadWritten = Loc (#bFileNumber)

bFileNumber(Byte) Filenumber, which identifies an opened file
lLastReadWritten(Long) Variable, whichsigned with the Position of last read or written Byte (1-based)

Пример вызова:

<source lang="vb"> 'open the file in BINARY mode Open "test.biN" For Binary As #2 Put #2 , B ' write a byte Put #2 , W ' write a word Put #2 , L ' write a long Ltemp = Loc(#2) + 1 ' get the position of the next byte Print Ltemp ; " LOC" ' store the location of the file pointer Print Lof(#2) ; " length of file" Print Fileattr(#2) ; " file mode" ' should be 32 for binary Put #2 , Sn ' write a single Put #2 , Stxt ' write a string

Flush #2 ' flush to disk Close #2 </source>

FileAttr

Возвращает режим открытия файлового потока.

bFileAttribut = FileAttr (bFileNumber)

bFileAttribut(Long) Режим:

1 - INPUT
2 - OUTPUT
8 - APPEND
32 - BINARY

bFileNumber(Byte) Идентификационный номер открытого файлового потока[3]

Пример вызова:

<source lang="vb"> 'open the file in BINARY mode Open "test.biN" For Binary As #2 Print Fileattr(#2) ; " file mode" ' should be 32 for binary Put #2 , Sn ' write a single Put #2 , Stxt ' write a string Close #2 </source>

Другие

Bload

Writes the Content of a File into SRAM.

This function writes the content of a file to a desired space in SRAM. A free handle is needed for this function.

BLoad sFileName, wSRAMPointer

sFileName(Long) Name of the File to be read
wSRAMPointer(Word) Variable, which holds the SRAM Address to which the content of the file should be written

Пример вызова:

<source lang="vb"> 'now the good old bsave and bload Dim Ar(100) As Byte , I As Byte For I = 1 To 100 Ar(i) = I ' fill the array Next

Wait 2

W = Varptr(ar(1)) Bsave "josef.img" , W , 100 For I = 1 To 100 Ar(i) = 0 ' reset the array Next

Bload "josef.img" , W ' Josef you are amazing !

For I = 1 To 10 Print Ar(i) ; " " ; Next Print </source>

Bsave

Save a range in SRAM to a Fileю

This function writes a range from the SRAM to a file. A free file handle is needed for this function.

BSave sFileName, wSRAMPointer, wLength

sFileName(Long) Name of the File to be written
wSRAMPointer(Word) Variable, which holds the SRAM Address, from where SRAM should be written to a File
wLength(Word) Count of Bytes from SRAM, which should be written to the file

Пример вызова:

<source lang="vb">'now the good old bsave and bload Dim Ar(100) As Byte , I As Byte For I = 1 To 100 Ar(i) = I ' fill the array Next

Wait 2

W = Varptr(ar(1)) Bsave "josef.img" , W , 100 For I = 1 To 100 Ar(i) = 0 ' reset the array Next

Bload "josef.img" , W ' Josef you are amazing !

For I = 1 To 10 Print Ar(i) ; " " ; Next Print </source>

Сноски

  1. 1 2 8.3: имя - 8 символов, расширение - 3 символа, разделитель(точка) - 1 символ, всего не более 12 символов
  2. 1 2 Если не указано, параметром считается последний файл, выбранный с помощью DIR
  3. 1 2 Принадлежит целому множеству 0..255, может быть переменной или константой. Используйте числа 1..127 для пользовательских идентификаторов. Для получения свободного идентификатора используйте функцию FreeFile(возвращает 128..255) Ошибка цитирования Неверный тег <ref>: название «identnumber» определено несколько раз для различного содержимого
  4. 1 2 Коды ошибок

См. также