Страница 1 из 2

FindFirstFile, FindNextFile...

Добавлено: 01 мар 2018, 15:26
Stasss
Здравствуйте!
Подскажите. Пытаюсь реализовать подобное http://map-info.ru/phpBB2/viewtopic.php ... 31b77feed6.
FindFirstFile отрабатывает успешно. А вот FindNextFile "валит" мапинфо.
..Fisrt.. успешно проходит, когда ..Next.. нет в скрипте (закомментирован), а когда есть ..Next.., то и ..First.. не делает ничего, МИ сразу "валится".
Вин 10 64, МИ 16 64. Может есть нюансы какие-то спустя время?

Причем, хэндлы получаются 9-значные, положит. и отрицат. Так что не совсем пойму в примерах по ссылке когда хэндл сравнивают с нулем или единицей. Вот -1 да, есть, когда нет файла..

Re: FindFirstFile, FindNextFile...

Добавлено: 01 мар 2018, 15:31
trir
код где?

Re: FindFirstFile, FindNextFile...

Добавлено: 01 мар 2018, 15:39
Stasss
Спойлер
Include "mapbasic.def"

define MAX_PATH 260

Type WIN32_FIND_DATA
dwFileAttributes As Integer
ftCreationTime As Float
ftLastAccessTime As Float
ftLastWriteTime As Float
nFileSizeHigh As Integer
nFileSizeLow As Integer
dwReserved0 As Integer
dwReserved1 As Integer
cFileName As String * MAX_PATH
cAlternate As String * 14
End Type

Declare function FindFirstFile lib "Kernel32" alias "FindFirstFileA"
(byval
lpFileName as string,
lpFindFileData as WIN32_FIND_DATA
) as integer

Declare function FindNextFile lib "Kernel32" alias "FindNextFileA"
(byval
hFindFile as integer, lpFindFileData as WIN32_FIND_DATA
) as integer

Declare function FindClose lib "Kernel32"
(byval hFindFile as integer) as integer

declare sub main
declare sub f1

dim curFiles() as string
'---------------------------------------------------------------------------------------
sub main

dialog
title "temp"
width 200 height 300
control button
ID 201
title "get class"
position 90, 5
calling find_class
control listbox
ID 202
title "list"
width 150 height 200
position 30, 25
disable

end sub
'--------------------------------------------------------------------------------------
sub f1

dim curPtch as string '--path to catalog
dim k as integer
dim hSearch as integer
dim WFD as WIN32_FIND_DATA
dim SearchStr as string

curPtch = ApplicationDirectory$( ) +"catalog\"
print "catalog: " + curPtch
if curPtch ="" then
note "Folder not found!"
exit sub
end if


k = 0
hSearch =FindFirstFile(curPtch+"*.tab", WFD)
'print "hSearch: " + hSearch
'print "WFD: " + WFD.cFileName

if hSearch <> -1 then
do
k=k+1
redim curFiles(k)
curFiles(k) = WFD.cFileName
loop while FindNextFile(hSearch, WFD) =1
hSearch = FindClose(hSearch)
'alter control 202 title from variable curFiles
'alter control 202 enable
else
note "no!"
exit sub
end if

end sub

Re: FindFirstFile, FindNextFile...

Добавлено: 01 мар 2018, 15:39
Stasss
Include "mapbasic.def"

define MAX_PATH 260

Type WIN32_FIND_DATA
dwFileAttributes As Integer
ftCreationTime As Float
ftLastAccessTime As Float
ftLastWriteTime As Float
nFileSizeHigh As Integer
nFileSizeLow As Integer
dwReserved0 As Integer
dwReserved1 As Integer
cFileName As String * MAX_PATH
cAlternate As String * 14
End Type

Declare function FindFirstFile lib "Kernel32" alias "FindFirstFileA"
(byval
lpFileName as string,
lpFindFileData as WIN32_FIND_DATA
) as integer

Declare function FindNextFile lib "Kernel32" alias "FindNextFileA"
(byval
hFindFile as integer, lpFindFileData as WIN32_FIND_DATA
) as integer

Declare function FindClose lib "Kernel32"
(byval hFindFile as integer) as integer

declare sub main
declare sub f1

dim curFiles() as string
'---------------------------------------------------------------------------------------
sub main

dialog
title "temp"
width 200 height 300
control button
ID 201
title "get class"
position 90, 5
calling f1
control listbox
ID 202
title "list"
width 150 height 200
position 30, 25
disable

end sub
'--------------------------------------------------------------------------------------
sub f1

dim curPtch as string '--path to catalog
dim k as integer
dim hSearch as integer
dim WFD as WIN32_FIND_DATA
dim SearchStr as string

curPtch = ApplicationDirectory$( ) +"catalog\"
print "catalog: " + curPtch
if curPtch ="" then
note "Folder not found!"
exit sub
end if


k = 0
hSearch =FindFirstFile(curPtch+"*.tab", WFD)
'print "hSearch: " + hSearch
'print "WFD: " + WFD.cFileName

if hSearch <> -1 then
do
k=k+1
redim curFiles(k)
curFiles(k) = WFD.cFileName
loop while FindNextFile(hSearch, WFD) =1
hSearch = FindClose(hSearch)
'alter control 202 title from variable curFiles
'alter control 202 enable
else
note "no!"
exit sub
end if

end sub

Re: FindFirstFile, FindNextFile...

Добавлено: 01 мар 2018, 15:40
Stasss
в общем-то почти все из источников....

Re: FindFirstFile, FindNextFile...

Добавлено: 01 мар 2018, 15:50
Stasss
когда блок If ...then отключен, принты успешно показывают имя и хэндл по первому файлу, а когда включен, до принтов и не доходит, сразу стоппинг...

Re: FindFirstFile, FindNextFile...

Добавлено: 01 мар 2018, 17:08
EvsYur
при каком событии FindNextFile(hSearch, WFD) вернет 1?

Re: FindFirstFile, FindNextFile...

Добавлено: 01 мар 2018, 17:21
Stasss
EvsYur писал(а): 01 мар 2018, 17:08при каком событии FindNextFile(hSearch, WFD) вернет 1?
так вот и я сомневаюсь в этом!
но, кажется, на вылет это не влияет.....
и вообще не совсем понимаю, что возвращает FindNextFile и FindClose...
..Next.. видимо тоже хэндл возвращает...

Re: FindFirstFile, FindNextFile...

Добавлено: 01 мар 2018, 17:56
EvsYur
The function returns 1 if another matching file was found, or 0 if no more matching files exist (or if an error occured).
. Похоже, по "0" надо выходить из цикла.

Re: FindFirstFile, FindNextFile...

Добавлено: 01 мар 2018, 18:07
Stasss
EvsYur писал(а): 01 мар 2018, 17:56Похоже, по "0" надо выходить из цикла.
так в коде "1" - это условие выполнения (продолжения) цикла и есть. будет "0" - цикл прервется. я так понимаю

И "0" и "1" это целочисленным типом или логическим, интересно?

Re: FindFirstFile, FindNextFile...

Добавлено: 01 мар 2018, 18:13
EvsYur
RTFM

Re: FindFirstFile, FindNextFile...

Добавлено: 01 мар 2018, 18:29
Stasss
EvsYur писал(а): 01 мар 2018, 18:13RTFM
благодарю...

Re: FindFirstFile, FindNextFile...

Добавлено: 01 мар 2018, 19:30
Stasss
пробую использовать FindFirstFileW при "подключенном" блоке с ..Next..
хэндл принимает "-1" и на if else соответственно заканчивается работа, но не вылетает ведь.
Но файлы не находит почему-то?

Таким же результатом заканчивается проба с ..First..A , но в начале пути поиска приписал "\\\\,\\" - т.е. также хэндл "-1" и файлы не находятся....
Не, тут, наверно, я гоню.....Просто путь меняется и, естественно, там файлов нет, вот и "-1".

А вот если путь верен, то все-таки ..First..A приводит к вылету, а ..W нет но с -1

Re: FindFirstFile, FindNextFile...

Добавлено: 01 мар 2018, 20:18
Stasss
сдается мне, проблема не синтаксисе операторов, а что-то системное.....
т.к. одиночный ..First.. работает, сначит список там у себя строит, а вот ..Next.. не хочет по этому списку идти...как-бы вообще не работает.
Win 10 64 En. Может что-то с какими-то системными настройками связано? региональными, языковыми, кодировочными?......
В пути и названиях таблиц русских букв нет.

Опять-таки переменной WFD успешно имя первой таблицы присваивается, эта же переменная и ..Nextом.. используется...но только в случае, когда нет ..Next.. в коде.
в общем я запутался вообще уже

Re: FindFirstFile, FindNextFile...

Добавлено: 01 мар 2018, 21:12
Stasss
В общем тема такая: запустил демо-код от James Moloney с сайта http://glab2007.narod.ru/d/mu.html
на MI16 64en также не пошла, вылет MIбез слов, без попытки что-то сделать.
А вот на MI15 32en все прошло на ура.
дело может в разрядности MI? и библиотеках каких-нить WinAPI....тут я не шарю((((
вот демо-код:

'--------------------------------------------------------------------------------------------------
'***** Directory Scan Example *****
' Copyright © January 2014 - Developed James Moloney
'
'This example demonstrates how to scan the windows directory using the Windows API kernel32.dll.
'Before you compile this code modify the strDir value and the filter type in the Main sub routine.
'
'WARNING! SOME CHANGES WERE MADE TO AN ORIGINAL CODE!
'
'Please feel free to use or modify this code for use in your application. This code is offered
'under the described GNU below. It would be appreciated if this code is used that there is a
'reference back to http://mapbasichelp.blogspot.com
'
'Kind regards
'James Moloney
'
'GNU GENERAL PUBLIC LICENSE
'This program is free software: you can redistribute it and/or modify
'it under the terms of the GNU General Public License as published by
'the Free Software Foundation, either version 3 of the License, or
'(at your option) any later version.
'This program is distributed in the hope that it will be useful,
'but WITHOUT ANY WARRANTY; without even the implied warranty of
'MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
'GNU General Public License for more details.
'You should have received a copy of the GNU General Public License
'along with this program. If not, see http://www.gnu.org/licenses/
'--------------------------------------------------------------------------------------------------

Include "MAPBASIC.def"

Type FILETIME
dwLowDateTime As Integer
dwHighDateTime As Integer
End Type

Type WIN32_FIND_DATA
dwFileAttributes As Integer
ftCreationTime As FILETIME
ftLastAccessTime As FILETIME
ftLastWriteTime As FILETIME
nFileSizeHigh As Integer
nFileSizeLow As Integer
dwReserved0 As Integer
dwReserved1 As Integer
cFileName As String * 260
cAlternate As String * 14
End Type

Define FILE_ATTRIBUTE_DIRECTORY 16

Declare Sub Main()

Declare Function GetFileList(ByVal strFilePath as String, ByVal strFileFilter as String, strFileList() as String) as Logical

Declare Function FindFirstFile Lib "kernel32" Alias "FindFirstFileA" (ByVal lpFileName As String, lpFindFileData As WIN32_FIND_DATA) As Integer
Declare Function FindNextFile Lib "kernel32" Alias "FindNextFileA" (ByVal hFindFile As Integer, lpFindFileData As WIN32_FIND_DATA) As Integer
Declare Function FindClose Lib "kernel32" (ByVal hFindFile As Integer) As Integer

'--------------------------------------------------------------------------------------------------
Sub Main()
OnError Goto CatchEx

Dim bResult As Logical
Dim strDir As String
Dim saFileNames() as String
Dim i as integer

Print chr$(12)

' strDir = "C:\Temp\"
strDir = LocateFile$(LOCATE_CUSTSYMB_DIR) ' Directory with users symbols

' bResult = GetFileList(strDir, ".tab" , saFileNames())
bResult = GetFileList(strDir, ".bmp" , saFileNames()) ' only *BMP files

If bResult = True Then

For i = 1 to UBound(saFileNames())
Print i & ": " & saFileNames(i)
Next

Note "Total files found: " & UBound(saFileNames())
Else
Note strDir & " Doesn't Exist"
End If

Done:
Exit Sub
CatchEx:
Note Error$()
Resume Done
End Sub
'--------------------------------------------------------------------------------------------------
Function GetFileList(ByVal strFilePath as String, ByVal strFileFilter as String, strFileList() as String) as Logical
OnError Goto CatchEx

Dim hFind As Integer
Dim wfd As WIN32_FIND_DATA

Dim strFileName as String
Dim iReturn as Integer
iReturn = 1

Dim i as Integer
i = 1

Dim strSubDirFileList() as String
Dim j as Integer

hFind = FindFirstFile(strFilePath & "*.*", wfd)

'Trim off any spaces
strFileName = LTrim$(RTrim$(wfd.cFileName))

If Len(strFileName) > 0 Then

Do While iReturn <> 0

If strFileName = "." or strFileName = ".." then
iReturn = FindNextFile(hFind, wfd)
strFileName = LTrim$(RTrim$(wfd.cFileName))
Else
strFileName = LTrim$(RTrim$(wfd.cFileName))
If wfd.dwFileAttributes = FILE_ATTRIBUTE_DIRECTORY then
iReturn = GetFileList(strFilePath & strFileName & "\", strFileFilter, strSubDirFileList())
For j = 1 to Ubound(strSubDirFileList)
ReDim strFileList(i)
strFileList(i) = strSubDirFileList(j)
i = i + 1
Next
iReturn = FindNextFile(hFind, wfd)

Else

If Right$(strFileName, Len(strFileFilter)) = strFileFilter then
ReDim strFileList(i)
strFileList(i)= strFilePath & strFileName
i = i + 1
End If

iReturn = FindNextFile(hFind, wfd)

End If

End If

Loop

End If

iReturn = FindClose(hFind)

GetFileList = true

Done:
Exit Sub
CatchEx:
Note Error$()
Resume Done
End Function
'--------------------------------------------------------------------------------------------------