Finding/creating a unique file from a path

Share your advanced PureBasic knowledge/code with the community.
Mistrel
Addict
Addict
Posts: 3415
Joined: Sat Jun 30, 2007 8:04 pm

Finding/creating a unique file from a path

Post 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
wallgod
User
User
Posts: 48
Joined: Wed Oct 06, 2010 2:03 pm

Re: Finding/creating a unique file from a path

Post by wallgod »

This is really useful, thank you!
Procrastinators unite... tomorrow!
Post Reply