Как узнать есть файл, или его нету?

Тема в разделе "WASM.BEGINNERS", создана пользователем TOLSTOPUZ, 7 июн 2008.

  1. TOLSTOPUZ

    TOLSTOPUZ New Member

    Публикаций:
    0
    Регистрация:
    26 апр 2008
    Сообщения:
    509
    Программа использует некий файл.
    Но предварительно надо убедиться, есть ли по этому самому адресу этот самый файл, или его там нету?
    Например
    C:\document.doc

    Есть такая апишка?
     
  2. Colibri

    Colibri New Member

    Публикаций:
    0
    Регистрация:
    8 май 2008
    Сообщения:
    117
    OpenFile("document.doc", &of, OF_EXIST);

    Вернет 1 если файл есть и -1 если нет.


    Код (Text):
    1. HFILE WINAPI OpenFile(
    2.   __in          LPCSTR lpFileName,
    3.   __out         LPOFSTRUCT lpReOpenBuff,
    4.   __in          UINT uStyle
    5. );
    6.  
    7. Parameters
    8. lpFileName
    9. The name of the file.
    10.  
    11. The string must consist of characters from the Windows character set. The OpenFile function does not support Unicode file names or opening named pipes.
    12.  
    13. lpReOpenBuff
    14. A pointer to the OFSTRUCT structure that receives information about a file when it is first opened.
    15.  
    16. The structure can be used in subsequent calls to the OpenFile function to see an open file.
    17.  
    18. The OFSTRUCT structure contains a pathname string member with a length that is limited to OFS_MAXPATHNAME characters, which is 128 characters. Because of this, you cannot use the OpenFile function to open a file with a path length that exceeds 128 characters. The CreateFile function does not have this path length limitation.
    19.  
    20. uStyle
    21. The action to be taken.
    22.  
    23. This parameter can be one or more of the following values.
    24.  
    25. Value Meaning
    26. OF_CANCEL
    27.  Ignored.
    28.  
    29. To produce a dialog box containing a Cancel button, use OF_PROMPT.
    30.  
    31. OF_CREATE
    32.  Creates a new file.
    33.  
    34. If the file exists, it is truncated to zero (0) length.
    35.  
    36. OF_DELETE
    37.  Deletes a file.
    38.  
    39. OF_EXIST
    40.  Opens a file and then closes it.
    41.  
    42. Use this to test for the existence of a file.
    43.  
    44. OF_PARSE
    45.  Fills the OFSTRUCT structure, but does not do anything else.
    46.  
    47. OF_PROMPT
    48.  Displays a dialog box if a requested file does not exist.
    49.  
    50. A dialog box informs a user that the system cannot find a file, and it contains Retry and Cancel buttons. The Cancel button directs OpenFile to return a file-not-found error message.
    51.  
    52. OF_READ
    53.  Opens a file for reading only.
    54.  
    55. OF_READWRITE
    56.  Opens a file with read/write permissions.
    57.  
    58. OF_REOPEN
    59.  Opens a file by using information in the reopen buffer.
    60.  
    61. OF_SHARE_COMPAT
    62.  For MS-DOS–based file systems, opens a file with compatibility mode, allows any process on a specified computer to open the file any number of times.
    63.  
    64. Other efforts to open a file with other sharing modes fail. This flag is mapped to the FILE_SHARE_READ|FILE_SHARE_WRITE flags of the CreateFile function.
    65.  
    66. OF_SHARE_DENY_NONE
    67.  Opens a file without denying read or write access to other processes.
    68.  
    69. On MS-DOS-based file systems, if the file has been opened in compatibility mode by any other process, the function fails.
    70.  
    71. This flag is mapped to the FILE_SHARE_READ|FILE_SHARE_WRITE flags of the CreateFile function.
    72.  
    73. OF_SHARE_DENY_READ
    74.  Opens a file and denies read access to other processes.
    75.  
    76. On MS-DOS-based file systems, if the file has been opened in compatibility mode, or for read access by any other process, the function fails.
    77.  
    78. This flag is mapped to the FILE_SHARE_WRITE flag of the CreateFile function.
    79.  
    80. OF_SHARE_DENY_WRITE
    81.  Opens a file and denies write access to other processes.
    82.  
    83. On MS-DOS-based file systems, if a file has been opened in compatibility mode, or for write access by any other process, the function fails.
    84.  
    85. This flag is mapped to the FILE_SHARE_READ flag of the CreateFile function.
    86.  
    87. OF_SHARE_EXCLUSIVE
    88.  Opens a file with exclusive mode, and denies both read/write access to other processes. If a file has been opened in any other mode for read/write access, even by the current process, the function fails.
    89.  
    90. OF_VERIFY
    91.  Verifies that the date and time of a file are the same as when it was opened previously.
    92.  
    93. This is useful as an extra check for read-only files.
    94.  
    95. OF_WRITE
    96.  Opens a file for write access only.
    97.  
    98.  
    99. Return Value
    100. If the function succeeds, the return value specifies a file handle.
    101.  
    102. If the function fails, the return value is HFILE_ERROR. To get extended error information, call GetLastError.
    103.  
    104. Remarks
    105. If the lpFileName parameter specifies a file name and extension only, this function searches for a matching file in the following directories and the order shown:
    106.  
    107. The directory where an application is loaded.
    108.  
    109. The current directory.
    110.  
    111. The Windows system directory.
    112.  
    113. Use the GetSystemDirectory function to get the path of this directory.
    114.  
    115. The 16-bit Windows system directory.
    116.  
    117. There is not a function that retrieves the path of this directory, but it is searched.
    118.  
    119. The Windows directory.
    120.  
    121. Use the GetWindowsDirectory function to get the path of this directory.
    122.  
    123. The directories that are listed in the PATH environment variable.
    124.  
    125. The lpFileName parameter cannot contain wildcard characters.
    126.  
    127. The OpenFile function does not support the OF_SEARCH flag that the 16-bit Windows OpenFile function supports. The OF_SEARCH flag directs the system to search for a matching file even when a file name includes a full path. Use the SearchPath function to search for a file.
    128.  
    129. A sharing violation occurs if an attempt is made to open a file or directory for deletion on a remote machine when the value of the uStyle parameter is the OF_DELETE access flag OR'ed with any other access flag, and the remote file or directory has not been opened with FILE_SHARE_DELETE share access. To avoid the sharing violation in this scenario, open the remote file or directory with OF_DELETE access only, or call DeleteFile without first opening the file or directory for deletion.
    130.  
    131. Requirements
    132. Client
    133.  Requires Windows Vista, Windows XP, or Windows 2000 Professional.
    134.  
    135. Server
    136.  Requires Windows Server 2008, Windows Server 2003, or Windows 2000 Server.
    137.  
    138. Header
    139.  Declared in WinBase.h; include Windows.h.
    140.  
    141. Library
    142.  Use Kernel32.lib.
    143.  
    144. DLL
    145.  Requires Kernel32.dll.
     
  3. Vov4ick

    Vov4ick Владимир

    Публикаций:
    0
    Регистрация:
    8 окт 2006
    Сообщения:
    581
    Адрес:
    МО
    FindFirstFile ?
     
  4. l_inc

    l_inc New Member

    Публикаций:
    0
    Регистрация:
    29 сен 2005
    Сообщения:
    2.566
    Но GetFileAttributes все-таки приличнее использовать.
     
  5. Explode Sense

    Explode Sense New Member

    Публикаций:
    0
    Регистрация:
    21 июл 2006
    Сообщения:
    130
    Адрес:
    Russia
    Например, проверить аттрибуты файла? И по результатам уже делать выводы о наличии файла или FindFirstFile
     
  6. TOLSTOPUZ

    TOLSTOPUZ New Member

    Публикаций:
    0
    Регистрация:
    26 апр 2008
    Сообщения:
    509
    Гм... Какие аттрибуты могут быть у несуществующего файла?

    допустим
    1 - несуществующий файл не директория
    2 - не существующий файл - не файл

    можно проверить это по порядку в 2 этапа.
    но с чем сравнивать -то, если файла нету?
    Не покажет ли программа ошибку?
    Например, что тут указать?

    cmp неизвестно что, FILE_ATTRIBUTE_DRECTORY

    ;#########################################

    Не факт, что она вернёт ИМЕННО ЭТУ ошибку... Вдруг что другое будет тоже с ошибкой на компе пользователя... Хотелось бы поймать отсутствие файла именно не на ошибке. а заловить хитро. Может правда аттрибутами как нить...
     
  7. Colibri

    Colibri New Member

    Публикаций:
    0
    Регистрация:
    8 май 2008
    Сообщения:
    117
    Вы хоть отладчиком или МСДН пользуетесь??
    если файла нет, функция вернет INVALID_FILE_ATTRIBUTES


    OpenFile()
    ФАКТ
    Если файла нету, функция вернет INVALID_HANDLE_VALUE (ака HFILE_ERROR)
     
  8. Explode Sense

    Explode Sense New Member

    Публикаций:
    0
    Регистрация:
    21 июл 2006
    Сообщения:
    130
    Адрес:
    Russia
    Эх... При всём уважении, почему бы не проверить самому? Если объекта (директории или файла) не существует, то в ответ 0xFFFFFFFF, если существует, но директория то 0x00000010.
     
  9. TOLSTOPUZ

    TOLSTOPUZ New Member

    Публикаций:
    0
    Регистрация:
    26 апр 2008
    Сообщения:
    509
    А если по размеру файла?
    Несуществующий файл не имеет размера больше нуля.
    Но он и не имеет размера ноль тоже... Забавно...
    Короче, вариантов вырисовывается масса...

    P.S.
    Меня всё время преследуют отличные идеи... Но я всегда оказываюсь быстрее...
     
  10. l_inc

    l_inc New Member

    Публикаций:
    0
    Регистрация:
    29 сен 2005
    Сообщения:
    2.566
    TOLSTOPUZ
    Прежде, чем оспаривать вполне правильные предложенные варианты, удосужились бы в MSDN глянуть. В частности по фукнциям GetFileAttributes (да да, Вы не ослышались: проверка атрибутов несуществующего файла. Набор атрибутов файла не ограничивается Вашим ущербным представлением о нём: это не только FILE_ATTRIBUTE_DIRECTORY) и GetLastError.
     
  11. TOLSTOPUZ

    TOLSTOPUZ New Member

    Публикаций:
    0
    Регистрация:
    26 апр 2008
    Сообщения:
    509
    Никто ничего не оспаривает.
    Этот метод общения называется диспут.
    Я спрашиваю, мне отвечают...
    Согласен, что я многого не знаю, иногда ленив,
    хитёр, (вот у вас тут выспрашиваю нахаляву...)
    значит заслуживаю хорошей интернет-порки!!!
    Но надеюсь, не будете больно бить Толстопуза.
    Всё-таки свой, воин дзена... :)
     
  12. roman_pro

    roman_pro New Member

    Публикаций:
    0
    Регистрация:
    9 фев 2007
    Сообщения:
    291
    TOLSTOPUZ
    http://gzip.rsdn.ru/article/qna/baseserv/fileexist.xml
     
  13. Shoorup

    Shoorup Member

    Публикаций:
    0
    Регистрация:
    20 сен 2007
    Сообщения:
    109
    У меня не получается
    Подскажите где ошибка:
    Код (Text):
    1. .386
    2. .model flat, stdcall
    3. option casemap:none
    4. include \masm32\include\kernel32.inc
    5. include \masm32\include\user32.inc
    6.  
    7. includelib \masm32\lib\kernel32.lib
    8. includelib \masm32\lib\user32.lib
    9.  
    10. .data
    11. MsgTextT db "Файл существует",0
    12. MsgTextF db "Такого файла нет",0
    13. MsgTitle db "Test",0
    14. .code
    15. start:
    16. invoke OpenFile "MesagaCPU.exe", &of, OF_EXIST
    17. cmp eax,1
    18. je true
    19. invoke MessageBox, 0, ADDR MsgTextF, ADDR MsgTitle, 0
    20. jmp exit
    21. true:
    22. invoke MessageBox, 0, ADDR MsgTextT, ADDR MsgTitle, 0
    23. exit:
    24. invoke ExitProcess, 0
    25. end start
    Отлично понимаю что вот тут: invoke OpenFile "MesagaCPU.exe", &of, OF_EXIST, и даже есть подозрение что второй параметр OFSTRUCT.
     
  14. wasm_test

    wasm_test wasm test user

    Публикаций:
    0
    Регистрация:
    24 ноя 2006
    Сообщения:
    5.582
    Чтобы узнать размер надо открыть файл. А если открыть файл то можно сразу сказать есть он или нет.
    Но проще использовать GetFileAttributes, куда передается не handle, а имя
     
  15. Colibri

    Colibri New Member

    Публикаций:
    0
    Регистрация:
    8 май 2008
    Сообщения:
    117
    Shoorup
    .data

    invoke OpenFile "MesagaCPU.exe", offset of, OF_EXIST

    и предварительно объвляешь ofstruct
     
  16. Shoorup

    Shoorup Member

    Публикаций:
    0
    Регистрация:
    20 сен 2007
    Сообщения:
    109
    Colibri
    а что нужно писать во второй параметр? :)
     
  17. Aspire

    Aspire New Member

    Публикаций:
    0
    Регистрация:
    19 май 2007
    Сообщения:
    1.028
    Растянули простой вопрос на 17 постов )))
    Имя файла, что же еще.
    Вернее указатель на строку с полным именем файла.
    invoke OpenFile, offset FileName, offset of, OF_EXIST

    FeleName db 'c:\program files\myprog\myfile.txt',0
     
  18. Vov4ick

    Vov4ick Владимир

    Публикаций:
    0
    Регистрация:
    8 окт 2006
    Сообщения:
    581
    Адрес:
    МО
    Great
    А функция поиска размер разве не возвращает?
     
  19. wasm_test

    wasm_test wasm test user

    Публикаций:
    0
    Регистрация:
    24 ноя 2006
    Сообщения:
    5.582
    Vov4ick
    А ну или так конечно...
     
  20. Shoorup

    Shoorup Member

    Публикаций:
    0
    Регистрация:
    20 сен 2007
    Сообщения:
    109
    Colibri,Aspire ничего не получается :dntknw:
    invoke OpenFile offset FileName, offset of, OF_EXIST - тут ошибку дает
    в дате объявил
    of db "dbablockc.dll",0
    FileName db "E:\masm32\dbablockc.dll",0
    Что делаю не так?