Pregunta

lets take an example. i have a folder having 20 files. lets assume that all files are over 1 mb.. my objective is to copy first 500 kb (ie the string which occupies first 500kb) and write it to another file. then loop it and do the same for each of the 20 files. the writing of files must happen in 20 individual files.

for example i have

               1.doc1.txt
               2.doc2.txt
               3.doc.exe
               4.doc.jpg
               so on

i want

             first 500kb of doc1.txt to be saved in dup1.txt,
             first 500kb of doc2.txt in dup2.txt and so on.

is it possible to do this using vbscript? if yes how??? looks really complex to me.. .. please help

¿Fue útil?

Solución

You could use an ADODB.Stream object for this:

Set stream = CreateObject("ADODB.Stream")
stream.Open
stream.Type = 1  'binary
stream.LoadFromFile "doc1.txt"
chunk = stream.Read(512000)
stream.Close

stream.Open
stream.Type = 1  'binary
stream.Write chunk
stream.SaveToFile "dup1.txt", 2
stream.Close

An input file can be split into several chunks using 2 Stream objects like this:

Set iStream = CreateObject("ADODB.Stream")
Set oStream = CreateObject("ADODB.Stream")

iStream.Open
iStream.Type = 1  'binary
iStream.LoadFromFile "doc1.txt"

oStream.Open
oStream.Type = 1  'binary
oStream.Write iStream.Read(512000)
oStream.SaveToFile "dup.txt", 2
oStream.Close

oStream.Open
oStream.Type = 1  'binary
oStream.Write iStream.Read(512000)
oStream.SaveToFile "dup1.txt", 2
oStream.Close

oStream.Open
oStream.Type = 1  'binary
oStream.Write iStream.Read(512000)
oStream.SaveToFile "dup2.txt", 2
oStream.Close

...

iStream.Close

This can be simplified by wrapping repeating code segments in a procedure or function:

Const chunksize = 512000

Sub WriteChunk(data, filename)
  Set oStream = CreateObject("ADODB.Stream")
  oStream.Open
  oStream.Type = 1  'binary
  oStream.Write data
  oStream.SaveToFile filename, 2
  oStream.Close
End Sub

Set iStream = CreateObject("ADODB.Stream")

iStream.Open
iStream.Type = 1  'binary
iStream.LoadFromFile "doc1.txt"

WriteChunk iStream.Read(chunksize), "dup.txt"
WriteChunk iStream.Read(chunksize), "dup1.txt"
WriteChunk iStream.Read(chunksize), "dup2.txt"
...

iStream.Close

Otros consejos

Use the .Read method of a read-opened TextStream to read the chunk from your input file and the .Write method of a write-open TextStream to write it to your output file.

Sample code:

>> Dim tsIn : Set tsIn = goFS.OpenTextFile("00.vbs")
>> Dim tsOut : Set tsOut = goFS.CreateTextFile("00.head")
>> tsOut.Write tsIn.Read(10)
>> tsIn.Close
>> tsOut.Close
>> WScript.Echo goFS.OpenTextFile("00.head").ReadAll()
>>
Option Exp
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top