Library tutorials & articles
Binary Files
Strings
Outputting and reading strings to a file is slightly different - in this case we do need to know how long the data is. So, if we output
Put #nFileNum, 1, "hello"
we need to know that the string we wrote was 5 characters in length to retreive the correct value again. First of all, lets assume that we do know this. How can we tell VB that the string is 5 characters in length, as there is no Length parameter for the Get statement?
What we do is initialize the string variable that we pass to Get beforehand, with the number of bytes we want to read. We normally do this using the Space$ function. For example,
sString = Space$(5)
fills sString with 5 spaces. Now, when we pass sString to the Get function, we retreive 5 characters. Try it! First, use
Dim nFileNum As Integer
nFileNum = FreeFile
Open App.Path & "example.bin" For Binary Access _
Write Lock Read Write As #nFileNum
Put #nFileNum, 1, "hello"
Close #nFileNum
to write the data to a file, and then use
Dim nFileNum As Integer, sString As String
nFileNum = FreeFile
Open App.Path & "example.bin" For Binary Access _
Read Lock Read Write As #nFileNum
sString = Space$(5)
Get #nFileNum, 1, sString
Close #nFileNum
Msgbox sString
to read the value back again.
Comments
Related articles
Related discussion
-
Run-time error '91'
by converter2009 (1 replies)
-
VB6 Runtime error 381 subsript out of range Error
by Uncle (2 replies)
-
passing and reading parameters from using Shell
by jigartoliya (0 replies)
-
Convert C++ code to VB6
by mawcot (4 replies)
-
listbox scrollbar
by Dennijr (10 replies)
Related podcasts
-
Christian Beauclair
14 mai 2008 (�mission #0074) ::.Christian Beauclair: Stratégies de migration VB6 vers .NET Nous discutons avec Christian Beauclair des stratégies de migration VB6 vers .NET. Entre autres, nous discutons comment utiliser le "VB 6 Code Advisor" et le "Interop Forms Toolkit" pour ajouter la puiss...
it helps me a lot, thanks![Big Smile [:D]](/emoticons/emotion-2a.gif)
Thanks it was very helpfull
I want to read a binary file whitch saved by a Grid Option.how Can i Read this file and retrieve data from file.
I am struggling for long time to display a GIF file on an ASP page. I have tried to return a GIF file in few formats
from a webservice.
Webservice returns the images as MemoryStream.GetBuffer(). Its an array of unsigned bytes.I also tried to return it
in base64 encoded format.
I can call this webservice in either of 2 ways
1) Directly from ASP -- It returns me this ..
ÿØÿàJFIF
`ÿÛC $.' ",#(7),01444'9=82<.342ÿÛC 2!!22222222222222222222222222222222222222222222222222ÿÀ(("ÿÄ ÿĵ}!1A <br> Qa"q2‘¡#B±ÁRÑð$3br‚ %&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyzƒ„…†‡ˆ‰Š’“”•–—˜™š¢£¤¥¦§¨©ª²³´µ¶·¸¹ºÂÃÄÅÆÇÈÉÊÒÓÔÕÖרÙÚáâãäåæçèéêñòóôõö÷øùúÿÄ ÿĵw!1 <br> AQaq"2B‘¡±Á #3RðbrÑ $4á%ñ&'()*56789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz‚ƒ„…†‡ˆ‰Š’“”•–—˜™š¢£¤¥¦§¨©ª²³´µ¶·¸¹ºÂÃÄÅÆÇÈÉÊÒÓÔÕÖרÙÚâãäåæçèéêòóôõö÷øùúÿÚ ?ôp2zW'©øîÒËR‚ XVæ}¢BNî«çùzž‹SÓ›WÒ <br> ®4ô»kG›d)Çð·}§úÃÇ/¬.tÛÉ-nâhæCÈ=Çb=Aõ®zÓ”v=l· FµÜÝßoÔõ‹ïh¶)½äÒ€ÐÃlf-ýÜŽÜœöãšsø–úÍÍ÷†/숽 œp99Qøf¹Ï‡ú…•½ôösÀ¿j¹[ÍŒ{§¶G§qŽõéò¬[<Å„hó '•>Æœ¦¯r1èágìÜ/æßåbµÌW–Ý@áá™w#Û§>‡Ž”Vƒv¦ª[#“ <br> µû, Oðsÿ ¯çEk sFç"’¥UÁlŽ’$JˆI˜@Î?õÄÇ£Çã+ÍsT™Þ8’e¶´ çã#¾Gç]´D ³m†O¥s> ;4ÛÍ4¡v—R4ÉŽ@ ãÓJ‰¤ä“:0³•:UCuoÌó½KK¾ÐuouE2Èã£Ì§¸¯R±ñ#Iá3â ”òf‰2) From VB(again I am returning byte array) which inturn is called by ASP -- I get the
same junk as above.
I need to convert it as a GIF file in my ASP page.
Can you guys suggest how it could by achived. I am open to change code at any layer.
Note - I am not getting any file back from VB or Web service. I am only getting it in some encoded format(byte array
or base64)
My ASP code is like this -
<%@ LANGUAGE="VBSCRIPT"%>
<% Response.Expires = 0
Response.Buffer = True
Response.clear
Response.contenttype = "image/gif"
Response.AddHeader "content-disposition", "inline; filename=MyMap.gif"
Set myEXE = CreateObject("ExFireSafeMapInfoTool.MapInfo")
varGetImage = myEXE.GenerateMapForHousehold()
RESPONSE.BinaryWrite (varGetImage)
'Value of varGetImage -- Dont know what format is this?
ÿØÿàJFIF
`ÿÛC $.' ",#(7),01444'9=82<.342ÿÛC 2!!22222222222222222222222222222222222222222222222222ÿÀ(("ÿÄ ÿĵ}!1A <br> Qa"q2‘¡#B±ÁRÑð$3br‚ %&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyzƒ„…†‡ˆ‰Š’“”•–—˜™š¢£¤¥¦§¨©ª²³´µ¶·¸¹ºÂÃÄÅÆÇÈÉÊÒÓÔÕÖרÙÚáâãäåæçèéêñòóôõö÷øùúÿÄ ÿĵw!1 <br> AQaq"2B‘¡±Á #3RðbrÑ $4á%ñ&'()*56789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz‚ƒ„…†‡ˆ‰Š’“”•–—˜™š¢£¤¥¦§¨©ª²³´µ¶·¸¹ºÂÃÄÅÆÇÈÉÊÒÓÔÕÖרÙÚâãäåæçèéêòóôõö÷øùúÿÚ ?ôp2zW'©øîÒËR‚ XVæ}¢BNî«çùzž‹SÓ›WÒ <br> ®4ô»kG›d)Çð·}§úÃÇ/¬.tÛÉ-nâhæCÈ=Çb=Aõ®zÓ”v=l· FµÜÝßoÔõ‹ïh¶)½äÒ€ÐÃlf-ýÜŽÜœöãšsø–úÍÍ÷†/숽 œp99Qøf¹Ï‡ú…•½ôösÀ¿j¹[ÍŒ{§¶G§qŽõéò¬[<Å„hó '•>Æœ¦¯r1èágìÜ/æßåbµÌW–Ý@áá™w#Û§>‡Ž”Vƒv¦ª[#“ <br> µû, Oðsÿ ¯çEk sFç"’¥UÁlŽ’$JˆI˜@Î?õÄÇ£Çã+ÍsT™Þ8’e¶´ çã#¾Gç]´D ³m†O¥s> ;4ÛÍ4¡v—R4ÉŽ@ ãÓJ‰¤ä“:0³•:UCuoÌó½KK¾ÐuouE2Èã£Ì§¸¯R±ñ#Iá3â ”òf‰%>
My VB Component function is something like this -
Public Function GenerateMapForHousehold() As Variant
Dim szFileName As String
Dim oSOAP As New SoapClient30 'Soap Type Library 3
Dim bytImage() As Byte
Dim szPicture As String
Dim iCount As Integer
Dim File As Integer
File = FreeFile
'Make the Call to Web Service to retrive the Image.
oSOAP.ClientProperty("ServerHTTPRequest") = True
oSOAP.MSSoapInit "http://localhost/WebService1/GetImage.asmx?WSDL"
bytImage = oSOAP.GetImage("bayshore.gif")
GenerateMapForHousehold3A = bytImage
'I can retreive this image in VB using this code -
'szPicture = App.Path & "\Test.gif"
'Open szPicture For Binary As File
'For iCount = LBound(bytImage) To UBound(bytImage) - 1
' Put #1, , bytImage(iCount)
'Next
'Close #1
'GenerateMapForHousehold = szPicture
'Set Form1.imgTest.Picture = LoadPicture(GenerateMapForHousehold)
End function
And web service(c#) method is something like this-
using System.IO;
using System.Drawing.Imaging;
public byte[] GetImage(string strFileName)
{
StreamWriter sr;
Byte sIn = new Byte();
Image MyImage;
MemoryStream MemStr = new MemoryStream();
MyImage = new Bitmap(Server.MapPath( strFileName));
MyImage.Save(MemStr, ImageFormat.Jpeg);
return MemStr.GetBuffer();
//I have 1 more function to return base64 encoded string but dont know how to use it further.
}
Please help.
Thanks
Mohit
e mail - mohitFL@hotmail.com
Dim FileNo As Integer
FileNo = FreeFile
Open ... ... As #FileNo
Get #FileNo, , FileStr
[courier new]// Mathias[/courier new]
Hi. I'm having a similar problem, I just can't get the header. I want to check if a .BMP file is in the right format. The header is BM, but i'm just getting M8 as header. That must be wrong
. How do you get the header? Isn't it just
I have the following from the tutorial:
Dim nFileNum As Integer, sString As String
nFileNum = FreeFile
Open "C:\Example\Example.txt" For Binary Access _
Read Lock Read Write As #nFileNum
sString = Space$(6)
Get #nFileNum, 1, sString
Close #nFileNum
MsgBox sString
[/Quote]
It reads the value in the file fine, but since i wrote the file in binary it reads it back in binary and all i get is a ""
Am i missing something... does the file need to be read in a certain way?
I don't know what I am doing wrong, but I would like to be able to read and write to *.exe and *.dll files. The problem is that it only gets the header ( MZ ). Does anyone know what I may have done wrong, or another method that can open EXE and DLL files? Thanks!
-vivi0
How do I find the size of the file?
[edit] Nevermind. LOF(1) seems to be it.
If everything you ever wanted to work with were an INI file, that'd be perfect. But if you want to make any sort of editor chances are you'll be using Binary file access.
Hi Shotgunner,
I assumed that a binary file that could be read by C/C++ could also be read in VB. There are constraints on how to do that but here goes. In the code I posted before I created a binary file. Here's the code I used to read it and write out the equivalent integer (or more correctly long) data in VB:
Private Sub cmdRead_Click()
Dim ibyte(2) As String * 1
Dim tot, temp As Long
Dim ind As Integer
For ind = 0 To 19
Get #1, , ibyte(1)
Get #1, , ibyte(2)
temp = Asc(ibyte(2)) * 2 ^ 8
tot = Asc(ibyte(1)) + temp
txtData(ind * 3).Text = tot
txtData((ind * 3) + 1).Text = Asc(ibyte(1))
txtData((ind * 3) + 2).Text = Asc(ibyte(2))
Next ind
End Sub
Private Sub mnuExitProgram_Click()
Unload frmBin
End Sub
Private Sub mnuFileOpen_Click()
Open "test.dat" For Binary As #1
cmdRead.Enabled = True
End Sub
Obviously I won't be sending you the forms.
Here's the C (or more correctly the VC++ ) code that accomplishes a similar purpose:
include <fstream.h>
include <iomanip.h>
int main()
{
unsigned ind, tot;
unsigned char byte[2];
ifstream infile("test.dat", ios::in );
for ( ind = 1; ind <= 20; ind++ )
{
infile.read( byte, 2 );
tot = byte[0] + ( byte[1] << 8 );
cout << setw(8) << ind << setw(8) << tot << setw(8) << (int)byte[0] << setw(8) << (int)byte[1] << endl;
}
return 0;
}
Both programs read in the binary data from test.dat and displayed (either to console or to form) the equivalent numerical data.
Is it possible to read a C++ written binary file into visual basic and write it again using vb then have it read by c++. If it is then can someone please tell me. also how do you write a typefef structure into a file using c++. Does anyone know. I would really appreciate it.
A binary file is a binary file regardless of which language creates it. The following code reads in a binary file 2 bytes at a time (the read statement) and then writes them to another binary file 2 bytes at a time (the write statement)
#include <fstream.h>
#include <iomanip.h>
int main()
{
int ind, tot;
unsigned char byte[2];
ifstream infile("2000_09_28_18_40_11_Sen2_Grp0.dat", ios::in );
ofstream outfile("test.dat", ios::binary );
for ( ind = 1; ind <= 20; ind++ )
{
infile.read( byte, 2 );
outfile.write( byte, 2 );
tot = byte[0] + ( byte[1] << 8 );
cout << setw(8) << ind << setw(8) << tot << setw(8) << (int)byte[0] << setw(8) << (int)byte[1] << endl;
}
return 0;
}
I plan to test test.dat later and make sure that VB can read it. But I have little doubt that it will. You may wonder what I was writing to the screen with cout. (This is important to consider.) Often binary files contain 2 byte integers split into two separate bytes. Here I was taking the bytes and recombining them into their original value. For example the first two number that are read are 208(byte[0] ) and 7 (byte[1]). Shifting the the 1 byte 7 8 places (the equivalent of multiplying by 256) and then adding it to byte[0] to make an integer 2 bytes long equals 2000. 7 * 256 + 208 = 1792 + 208 = 2000 or looked at another way 00000111 010110000 is a 16 bit representation of 2000.
I hope this helps.
David
And don't forget, data files shouldn't be written to the registry.
The Len() function returns null if the file is open in binary mode. Use the LOF() function instead.
Another thing, String() function is better to use than Space() function because if you have used value bigger than new value, Space() only fills string with spaces, leaving the size as is, but String() resizes the strng.
This is a 2 ways method, if your program very much independent on settings inside the INI files you just have to read and write the INI files at all times.
Or if ur program is mostly put the value inside the registry for a one-time settings of something in conjunction to the system setting, registry would be better.
But i prefer using INI files since it can be separated from the syste, registry and avoid corruption.
One more thing is in registry, you can organize ur setting in parent and child relationship but not INI file.
Since you can do the same kind of stuff like this and save it to the registry, which is easier, why use binary files? I could see it if you had a LOT of values, but then wouldn't you just use and INI file or something for conveienience? I guess keeping things secret, like passwords, you might use a bin file for, but what could it be used for other than that?
This thread is for discussions of Binary Files.
Leave a comment
Sign in or Join us (it's free).
Related tags
visual basic