Solved

some "basic" questions !!!

Posted on 2000-03-08
24
213 Views
Last Modified: 2010-05-02
Hi,

I am used to program in Delphi and C/C++, but I need some information about VB6.

1) is it possible to make console programs with VB6

2) how do I read the stdin and write to the stdout in a console program in VB6

3) how can I get the command line arguments in VB6 (I tried the Win32 GetCommandLine function, without success)

4) how can I read and write binaries structures in files (seems that the open - print / write - close functions does not allow it)

5) When I call the function ReadFile, the VB program crashes with the following Application Error message:
The instruction at "ox653432bc" referenced memory at "0x000000008". The memory could not be "read".
What happens?


Please, answer with examples to thoses questions.

Thanks
0
Comment
Question by:poupou
  • 9
  • 3
  • 3
  • +7
24 Comments
 
LVL 10

Accepted Solution

by:
caraf_g earned 200 total points
ID: 2596331
1) No

2) see 1)

3) Use Command$
Dim strText As String
strText = Command$

4) Open for binary (see next comment)

5) Don't use the file scripting, just use normal file functions. Open, Close, Get, Put etc.

0
 
LVL 10

Expert Comment

by:caraf_g
ID: 2596332
Open Statement
     

Enables input/output (I/O) to a file.

Syntax

Open pathname For mode [Access access] [lock] As [#]filenumber [Len=reclength]

The Open statement syntax has these parts:

Part Description
pathname Required.String expression that specifies a file name — may include directory or folder, and drive.
mode Required.Keyword specifying the file mode: Append, Binary, Input, Output, or Random. If unspecified, the file is opened for Random access.
access Optional. Keyword specifying the operations permitted on the open file: Read, Write, or Read Write.
lock Optional. Keyword specifying the operations restricted on the open file by other processes: Shared, Lock Read, Lock Write, and Lock Read Write.
filenumber Required. A validfile number in the range 1 to 511, inclusive. Use the FreeFile function to obtain the next available file number.
reclength Optional. Number less than or equal to 32,767 (bytes). For files opened for random access, this value is the record length. For sequential files, this value is the number of characters buffered.


Remarks

You must open a file before any I/O operation can be performed on it. Open allocates a buffer for I/O to the file and determines the mode of access to use with the buffer.

If the file specified by pathname doesn't exist, it is created when a file is opened for Append, Binary, Output, or Random modes.

If the file is already opened by another process and the specified type of access is not allowed, the Open operation fails and an error occurs.

The Len clause is ignored if mode is Binary.

Important   In Binary, Input, and Random modes, you can open a file using a different file number without first closing the file. In Append and Output modes, you must close a file before opening it with a different file number.

0
 
LVL 10

Expert Comment

by:caraf_g
ID: 2596340
Processing Files with Older File I/O Statements and Functions


Ever since the first version of Visual Basic, files have been processed using the Open statement and other related statements and functions (listed below). These mechanisms will eventually be phased out in favor of the FSO object model, but they are fully supported in Visual Basic 6.0.

If you can design your application to use database files, you will not need to provide direct file access in your application. The data control and bound controls let you read and write data to and from a database, which is much easier than using direct file-access techniques.

However, there are times when you need to read and write to files other than databases. This set of topics shows how to process files directly to create, manipulate, and store text and other data.

File Access Types
By itself, a file consists of nothing more than a series of related bytes located on a disk. When your application accesses a file, it must assume what the bytes are supposed to represent (characters, data records, integers, strings, and so on).

Depending upon what kind of data the file contains, you use the appropriate file access type. In Visual Basic, there are three types of file access:

Sequential — For reading and writing text files in continuous blocks.


Random — For reading and writing text or binary files structured as fixed-length records.


Binary — For reading and writing arbitrarily structured files.
Sequential access is designed for use with plain text files. Each character in the file is assumed to represent either a text character or a text formatting sequence, such as a newline character (NL). Data is stored as ANSI characters. It is assumed that a file opened for random access is composed of a set of identical-length records. You can employ user-defined types to create records made up of numerous fields — each can have different data types. Data is stored as binary information.

Binary access allows you to use files to store data however you want. It is similar to random access, except there are no assumptions made about data type or record length. However, you must know precisely how the data was written to the file to retrieve it correctly.

For More Information   To learn more about file access types, see "Using Sequential File Access," "Using Random File Access," and "Using Binary File Access."

File Access Functions and Statements
The following functions are used with all three types of file access:

Dir FileLen LOF
EOF FreeFile Seek
FileCopy GetAttr SetAttr
FileDateTime Loc  


The following table lists all of the file access statements and functions available for each of the three types of direct file access.

Statements & Functions Sequential Random Binary
Close X X X
Get  X X
Input( ) X  X
Input # X  
Line Input # X  
Open X X X
Print # X  
Put  X X
Type...End Type  X  
Write # X  


For More Information   For additional information on file access functions and statements, look up the function or statement topic in the index.

0
 
LVL 10

Expert Comment

by:caraf_g
ID: 2596342
Using Binary File Access


The File System Object model does not provide binary file creation or access methods. If you need to create or read binary files, this information will help you do so.

Binary access gives you complete control over a file, because the bytes in the file can represent anything. For example, you can conserve disk space by building variable-length records. Use binary access when it is important to keep file size small.

Note   When writing binary data to a file, use a variable that is an array of the Byte data type, instead of a String variable. Strings are assumed to contain characters, and binary data may not be properly stored in String variables.

Opening a File for Binary Access
To open a file for binary access, use the following syntax for the Open statement:

Open pathname For Binary As filenumber

As you can see, Open for binary access differs from Open for random access in that Len = reclength is not specified. If you include a record length in a binary-access Open statement, it is ignored.

Storing Information in Variable-Length Fields
To best appreciate binary access, consider a hypothetical Employee Records file. This file uses fixed-length records and fields to store information about employees.

Type Person
   ID               As Integer
   MonthlySalary      As Currency
   LastReviewDate      As Long
   FirstName         As String * 15
   LastName            As String * 15
   Title            As String * 15
   ReviewComments      As String * 150
End Type

Regardless of the actual contents of the fields, every record in that file takes 209 bytes.

You can minimize the use of disk space by using binary access. Because this doesn’t require fixed-length fields, the type declaration can omit the string length parameters.

Type Person
   ID               As Integer
   MonthlySalary      As Currency
   LastReviewDate      As Long
   FirstName         As String
   LastName            As String
   Title            As String
   ReviewComments      As String
End Type

Public Empl As Person      ' Defines a record.

Each employee record in the Employee Records file now stores only the exact number of bytes required because the fields are variable-length. The drawback to binary input/output with variable-length fields is that you can’t access records randomly — you must access records sequentially to learn the length of each record. You can seek directly to a specified byte position in a file, but there is no direct way to know which record is at which byte position if the records are of variable length.

For More Information   For additional information on binary file access, see "Open Statement."

0
 
LVL 10

Expert Comment

by:caraf_g
ID: 2596343
Hope this helps
0
 
LVL 10

Expert Comment

by:caraf_g
ID: 2596354
"These mechanisms will eventually be phased out in favor of the FSO object "

Total BS. They can't get rid of them for reasons of backward compatibility. Thank Bill.
0
 
LVL 43

Expert Comment

by:TimCottee
ID: 2596355
I can possibly give pointers on a couple of these;

2) use strCommandLine = Command()

This will return a string containing the arguments sent to the application, you will then need to chop the string up on commas/spaces etc to get individual arguments, there is an example of this in help, look up "Command Function" in the index

4) For binary read write, you need to open the file for binary and use binary read and write commands:

Dim ary100Chars() As Byte

Open "MyFile.bin" For Binary Access Write As #1
ary100Chars = InputB (100,#1)
Close #1

will get the first 100 characters from the file.
0
 
LVL 43

Expert Comment

by:TimCottee
ID: 2596364
But caraf_g has given you much, much more info than me, never mind I will try to be quicker next time!
0
 
LVL 3

Expert Comment

by:3rsrichard
ID: 2596366
1) is it possible to make console programs with VB6
No, use VC++ or other.  VB requires some of the Windows support programs.

2) how do I read the stdin and write to the stdout in a console program in VB6
You don't read or write in that way.  You create a text-box (or other equal) and either write to it or allow the user to write to it.

3) how can I get the command line arguments in VB6 (I tried the Win32 GetCommandLine function, without success)
There is a VB command called "Command" which will fetch the command line parameters for you.

4) how can I read and write binaries structures in files (seems that the open - print / write - close functions does not allow it)
One of the "open" parameters for files is "BINARY" to allow you to read/write binary data.

5) When I call the function ReadFile, the VB program crashes with the following Application Error message:
The instruction at "ox653432bc" referenced memory at "0x000000008". The memory could not be "read".
What happens?
Sounds like you passed an un-initialized parameter.  Thats a reference to a part of memory that shouldn't have any program data.
0
 
LVL 15

Expert Comment

by:ameba
ID: 2596557
>1) is it possible to make console programs with VB6
Yes. See http://www.saurik.com/ Goto Samples, smpConsole
0
 
LVL 14

Expert Comment

by:wsh2
ID: 2596614

1.  Yes.. you can write console like programs in Visual Basic, but they are not quite as simple as DOS was years ago. To write them in VB, you create a VB program that contains a series of SHELL commands (run program and wait or run asynchroniously).. and then interrogate the result through whatever means, you the programmer decide to use for interprocess communication. Interprocess communications can be as simple as dropping a temporary disk work file that transports program to program information, VB ActiveX.EXE's that can provide virtually direct program callback / return code routines, to using (non native VB) operating system API calls to hook a process's messages. The tools are certainly there.. <smile>.

2.  As windows is a multitasking operating system.. the concept of stdin / stdout as we know it.. no longer exists. You have to write your own graphical interface. Fortunately, writing this in VB is a VERY easy thing to do.. pop up a form in design mode.. add a couple of controls and the logic behind them.. SHELL out your processes and you can have the program report back whatever you like.. with a very professional look and feel.

3.  There are a couple of ways to read  command line parameters.. one.. is to use the Windows API.. <groan>.. or two.. use the VB Command() function.. <smile>.

4.  The best way to read and write user defined data types is to open the file in BINARY mode, and then use Gets and Puts to manuever through it.

    Open filename1 For BINARY ACCESS READ as #1
    Open filename2 For BINARY ACCESS WRITE as #2
    Dim udtBuffer as udtRecordType
    Get #1,,udtBuffer
    Put #2,,udtBuffer

5.  As ReadFile is NOT a VB command, but a user written routine for which I don't have the code.. I have no idea what caused the exception. Could be there was no buffer allocated.. or perhaps it read past EOF.. who knows?
0
 
LVL 10

Expert Comment

by:caraf_g
ID: 2596685
Wow ameba, not bad!
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 15

Expert Comment

by:ameba
ID: 2596758
Thanks for checking it, caraf_g.
0
 
LVL 20

Expert Comment

by:hes
ID: 2596902
0
 

Expert Comment

by:rubenz_vm
ID: 2598964
Hi!

I wonder why everyone is giving comments but not answers. I am new to this, could someone explain?

I will answer only your 3rd question.

First, copy the GetCommandLine function from VB Help (which is the example for the 'Command function') and copy into a module then, put the following codes into Sub Main or into another sub or function:

Sub Main()
Dim Arg As Variant
Arg = GetCommandLine()

If (LCase(Arg(1)) = "/help") then Help
'To load the Help sub or function

'The first parameter will be Arg(1), the
'second will be Arg(2) and so on.
'
'However, to find out whether there are
'no command line parameters passed into
'the program, use:

If (Command() = "") then MainForm.Show
'To load the main form.

End Sub
0
 
LVL 14

Expert Comment

by:wsh2
ID: 2599057
Hello rubenz vm.. <smile>. The practice of leaving comments rather than answers, is to allow everyone that passes by the question the opportunity to add their thoughts to the topic at hand. Many times, there is more than one way to solve a problem.. and the questioner is accorded the ultimate responsibility of deciding which answer best serves his/her given purpose.. and as such will accord the author expert points and a letter grade multiplier. With time, you will be surprised at what others can find and contribute.. all to the gain of one avid expert to another.. <smile>.

Now.. there are circumstances when questions will be absolutely obvious.. and it is those cases.. when you are absolutely positively certain that your answer is 100% pure, foolproof and that there could never ever possibly be a better solution.. and it is those times that you hit the Answer button and lock the question forcing the questioner to respond.. (sometimes before the best solution has been presented.. ofttimes, bringing down the wrath of one expert upon another.. <guilty look.. ahem>).

Naturally, as you probably can already tell.. MY answers are ALWAYS.. 100% pure, foolproof and.. er.. uh.. <gulp>.. oh nevermind.. as you can see.. I now leave Comments.. <lol>.

All in all.. if your answer is timely, unambiguous and respectfully written to the level of your questioner, you will find that your Expert points will amass rather quickly.. even if not, I am certain you will enjoy the time you have spent here.. <smile>.

Once again.. Welcome.
0
 
LVL 14

Expert Comment

by:mcrider
ID: 2599250
Yes it is possible to create VB console programs... See http://www.experts-exchange.com/jsp/qShow.jsp?ta=visualbasic&qid=10289451  


Cheers!®©
0
 
LVL 4

Expert Comment

by:amit_panjwani
ID: 2599728
i can give u answers for 3 n 4
will u award me some  points for that ??
0
 
LVL 10

Expert Comment

by:caraf_g
ID: 2599757
You joking? The answers for 3 and 4 have already been given.

Anyway this is not a barter ground. If you have answers, just give them. If you don't have the full answer to the question, just comment. And if your comments are very good, trust that the asker will have the decency to post a dummy question "X points for You" to reward you.
0
 
LVL 15

Expert Comment

by:ameba
ID: 2599918
That was run-time error x00003&4: The other peoples' posts could not be "read".  :)
0
 

Author Comment

by:poupou
ID: 2600751
Hi,

thanks for the numerous answers

I will give the 200 points to caraf_g, for its quick answers (but he needs to propose his answer).

I tried to create a console program with the ameba and hes's propositions. Both work fine, but still does not answer my need. See below the new question about CGIs.

Please, look at my new and more precises questions:
      "Application Error crashes the program",
      "Writing CGI in VB6, with console mode program"
0
 

Author Comment

by:poupou
ID: 2600800
Sorry for the CGI question. I just found out how to do it with the sample code from http://pw2.netcom.com/~obrienk/index.html

So I wont ask it :-)
0
 

Author Comment

by:poupou
ID: 2600813
see comment above
0
 
LVL 10

Expert Comment

by:caraf_g
ID: 2600875
Thanks poupou,

I didn't propose an answer because I wasn't satisfied myself that my suggestions were 100% correct. You thought they were fine, so you accepted my comment as an answer; the option is there for situations just like that.

Anyway, thank you very much for a significant amount of points! I'm glad I could be of some help.
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Most everyone who has done any programming in VB6 knows that you can do something in code like Debug.Print MyVar and that when the program runs from the IDE, the value of MyVar will be displayed in the Immediate Window. Less well known is Debug.Asse…
Enums (shorthand for ‘enumerations’) are not often used by programmers but they can be quite valuable when they are.  What are they? An Enum is just a type of variable like a string or an Integer, but in this case one that you create that contains…
Get people started with the process of using Access VBA to control Excel using automation, Microsoft Access can control other applications. An example is the ability to programmatically talk to Excel. Using automation, an Access application can laun…
Show developers how to use a criteria form to limit the data that appears on an Access report. It is a common requirement that users can specify the criteria for a report at runtime. The easiest way to accomplish this is using a criteria form that a…

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now