Page 1 of 1

Finding/creating a unique file from a path

Posted: Thu Oct 07, 2010 9:02 am
by Mistrel
A slight variation from the code I posted previously for creating a unique directory:

http://www.purebasic.fr/english/viewtop ... 12&t=43884

Code: Select all

Procedure.s GetUniqueFile(TargetPath.s, CreateFile.b=#False, BaseName.s="", RandomLength.a=32, Limit.l=1000000)
  Protected NewFile.s
  Protected i
  Protected FileID
  
  ;/ Verify that the path does not already exist
  If Not FileSize(TargetPath.s)=-2
    ProcedureReturn ""
  EndIf
  
  ;/ Ensure a trailing slash
  If Not Right(Trim(TargetPath.s,"/"),1)="\"
    TargetPath.s+"\"
  EndIf
  
  ;/ If the attempt limit is invalid then return
  If Limit<= 0
    ;/ Failed
    ProcedureReturn ""
  EndIf
  
  ;/ If the random length is invalid and no base name is specified then return
  If Not BaseName.s And RandomLength<= 0
    ;/ Failed
    ProcedureReturn ""
  EndIf
  
  ;/ If no base name is specified then use a random string of numbers and integers of length RandomLength
  If Not BaseName.s
    NewFile.s=""
    Repeat
      For i=1 To RandomLength
        If Random(1)=1
          NewFile.s+Chr(Random(25)+65)
        Else
          NewFile.s+Str(Random(9))
        EndIf
      Next i
      
      Limit-1
      
      ;/ If the attempt limit has been reached then return
      If Not Limit
        ;/ Failed
        ProcedureReturn ""
      EndIf
      
      If CreateFile
        ;/ If the path was successfully created then return
        If FileSize(TargetPath.s+NewFile.s)=-1
          FileID=CreateFile(#PB_Any,TargetPath.s+NewFile.s)
        EndIf
        
        If FileID
          CloseFile(FileID)
          ProcedureReturn NewFile.s
        EndIf
      Else
        ;/ If the path was verified as available then return
        If FileSize(TargetPath.s+NewFile.s)=-1
          ProcedureReturn NewFile.s
        EndIf
      EndIf
    ForEver
  EndIf
  
  For i=0 To Limit-1
    NewFile.s=BaseName.s+Str(i)
    
    If Len(NewFile.s)>255
      ProcedureReturn ""
    EndIf
    
    If CreateFile
      ;/ If the path was successfully created then return
      If FileSize(TargetPath.s+NewFile.s)=-1
        FileID=CreateFile(#PB_Any,TargetPath.s+NewFile.s)
      EndIf
      
      If FileID
        CloseFile(FileID)
        ProcedureReturn NewFile.s
      EndIf
    Else
      ;/ If the path was verified as available then return
      If FileSize(TargetPath.s+NewFile.s)=-1
        ProcedureReturn NewFile.s
      EndIf
    EndIf
  Next i
  
  ProcedureReturn ""
EndProcedure

Re: Finding/creating a unique file from a path

Posted: Thu Oct 14, 2010 8:01 pm
by wallgod
This is really useful, thank you!