Jump to content


Photo

get next file or previous file in a directory


  • Please log in to reply
4 replies to this topic

#1 random11

random11
  • Members
  • 98 posts

Posted 27 December 2011 - 06:00 AM

Ok so I have a path and i want to find the next file or previous in the same directory.

Example:

Say that I am working with a file "file4.txt" its located in "C:\temp"

And all the files in "C:\temp" are as follows:
C:\temp\file1.txt
C:\temp\file2.txt
C:\temp\file3.txt
C:\temp\file4.txt
C:\temp\file5.txt
C:\temp\file6.txtI want to be able to get the next file and the previous file. IE file3 and file5 how do I do this?

And obv assume that you dont know what the files in the directory are... but you do know what the current file and path is (C:\temp\file4.txt)

#2 random11

random11
  • Members
  • 98 posts

Posted 27 December 2011 - 07:27 AM

ok so for anyone out there this is what i did:

FileList =  ; Initialize to be blank.

Loop, %pathVar%\*.*, 0
    FileList = %FileList%%A_LoopFileLongPath%`n

prev = ;
nex = ;
indexVar = -1
found = 0

Loop, parse, FileList, `n
{
    if(A_LoopField = fileVar)
    {
        indexVar = %A_Index%
        found = 1
    }
    if( A_Index = indexVar + 1 and found = 1)
    {
        nex = %A_LoopField%
        break
    }
}

Loop, parse, FileList, `n
{
    if( A_Index = indexVar - 1 and found = 1)
    {
        prev = %A_LoopField%
        break
    }
}

MsgBox, File previous is %prev% and next is %nex% index is %indexVar%.

This is a little redundant because you loop through all the files twice. If anyone has a better way please let me know.

#3 Alpha Bravo

Alpha Bravo
  • Members
  • 863 posts

Posted 27 December 2011 - 08:27 AM

good one, that got me thinking.
I wouldn't call it a "better" way but loops only once.
Loop, %A_Desktop%\ahk\*.ahk, 0
{
    if (A_LoopFileName = "temp.ahk")
    {
        Found = 1
        FilePrev := Prev 
    }
    if Found
        Counter ++
    
    Prev := A_LoopFileName
    
    if (Counter = 2)
    {
        FileNext := A_LoopFileName
        break
    }
}
MsgBox % "Previouse file = "FilePrev "`nNext File = " FileNext


#4 Odlanir

Odlanir
  • Members
  • 754 posts

Posted 27 December 2011 - 08:53 AM

Requires AHK_L
fl := Object(), pathvar := "C:\temp"
Loop, %pathVar%\*.*, 0
	fl.Insert(A_LoopFileLongPath)
currFile := pathVar "\file4.txt"
loop, % fl.Maxindex()
	if ( currfile = fl[a_index] )
		msgbox % "Prev : " fl[a_index -1] "`nNext : " fl[a_index + 1]


#5 Alpha Bravo

Alpha Bravo
  • Members
  • 863 posts

Posted 27 December 2011 - 08:56 AM

or maybe
Loop, %A_Desktop%\ahk\*.ahk, 0
{
    Array%A_Index% := A_LoopFileName
    if (A_LoopFileName = "temp.ahk")
        Found := A_Index
}
Prev := Found - 1
Next := Found + 1
MsgBox % "Previouse file = " Array%Prev% "`nNext File = " Array%Next%

Edit: Odlanir beat me to it in style