Thursday, February 3, 2011

Read a Flat file and updated specific word.

Problem: Find the ‘QQ’ word and next word should replace with user input

Logic:
  1. Read Line by Line from text file and storing into Array
  2. Updating array if QQ word found
  3. Writing into File again
StringFile.txt contains:

11;12;xxxxxxxx;6666;77777;7777777;uuuu;ayex345;QQ;yyy;w434;ccc;
1q5;9s9;2f; 
' ################ Function call #########################
call ReadFromFile()

' ############### Function defination #####################
Function ReadFromFile()

          Const ForReading = 1
          Set objFSO = CreateObject("Scripting.FileSystemObject")
          Set objFile = objFSO.OpenTextFile("d:\StringFile.txt", ForReading)
          Dim arrFileLines()
          i = 0
          Do Until objFile.AtEndOfStream
                ReDim Preserve arrFileLines(i)
                 arrFileLines(i) = objFile.ReadLine
                i = i + 1
         Loop
         objFile.Close

         Call UpdateArrayValue(arrFileLines) ' Update array
         Call WriteArrIntoFiles(arrFileLines) ' writing file

End Function

Function UpdateArrayValue(arrFileLines)
     
       For K = 0 to Ubound(arrFileLines)
               NewArr = Split(arrFileLines(K), ";")
               For j = 0 To UBound(NewArr)
                        If NewArr(j) = "QQ" Then
                                    NewArr(j + 1) = "xxx"   ' xxx is user input value
                        End If
               Next
               UpdatedNewArr = Join(NewArr, ";")
               arrFileLines(K) = UpdatedNewArr
      Next
End Function

Function WriteArrIntoFiles(Arr)

              Const ForWriting = 2
              Set objFSO = CreateObject("Scripting.FileSystemObject")
              Set f = objFSO.GetFile("d:\StringFile.txt")
              Set Ln = f.OpenAsTextStream(ForWriting)
              For j = 0 To UBound(Arr)
                    Ln.WriteLine (Arr(j))
              Next
              Ln.Close
End Function

No comments: