Solved

Simple Q - How to create a file

Posted on 2002-07-25
11
158 Views
Last Modified: 2010-05-18
Hi,
I want to Create a simple text file
Add a Line into it
read a line from it
and save the file to the HD.
Please give an example code in VB
(with or w/o using COM Objetcs).
Thanks,
TheShark
0
Comment
Question by:TheShark8
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
11 Comments
 
LVL 28

Expert Comment

by:vinnyd79
ID: 7177095
This will create a text .If it does exist it will be overwritten:

Open "C:\somefile.txt" for output as #1
Print #1,"Hello,this will print on line 1"
Print #1,"Hello,this will print on line 2"
Close #1

This will also create a text file,but will add to the file if it exists:

Open "C:\somefile.txt" for append as #1
Print #1,"Hello,this will print on line 1"
Close #1

To read from the file 1 line at a time:
Open "C:\somefile.txt" for input as #1
Do Until eof(1)
Line input #1 G$
Msgbox G$
Loop
Close #1

The #1 represents the open file.If you were to 2 files at once,you could use #2 for the second file. If you are working with alot of files you could use 'FreeFile' to get the next available file#.
0
 
LVL 28

Accepted Solution

by:
vinnyd79 earned 20 total points
ID: 7177112
oops,
when you read the file there should be a "," after line input #1 in the above example.

Open "C:\somefile.txt" for input as #1
Do Until eof(1)
Line input #1, G$
Msgbox G$
Loop
Close #1

0
 
LVL 2

Expert Comment

by:damienm
ID: 7177118
You can also use filesystemobjects in VB.  There should be examples in help files

e.g.  to create a file and write data use something like

Sub CreateFile()
   Dim fso, tf
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set tf = fso.CreateTextFile("c:\testfile.txt", True)
   ' Write a line with a newline character.
   tf.WriteLine("Testing 1, 2, 3.")
   ' Write three newline characters to the file.        
   tf.WriteBlankLines(3)
   ' Write a line.
   tf.Write ("This is a test.")
   tf.Close
End Sub

For reding a line

Sub ReadFiles
   Dim fso, f1, ts, s
   Const ForReading = 1
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set f1 = fso.CreateTextFile("c:\testfile.txt", True)
   ' Write a line.
   Response.Write "Writing file <br>"
   f1.WriteLine "Hello World"
   f1.WriteBlankLines(1)
   f1.Close
   ' Read the contents of the file.
   Response.Write "Reading file <br>"
   Set ts = fso.OpenTextFile("c:\testfile.txt", ForReading)
   s = ts.ReadLine
   Response.Write "File contents = '" & s & "'"
   ts.Close
End Sub
0
MS Dynamics Made Instantly Simpler

Make Your Microsoft Dynamics Investment Count  & Drastically Decrease Training Time by Providing Intuitive Step-By-Step WalkThru Tutorials.

 
LVL 3

Expert Comment

by:PNJ
ID: 7177207
vinnyd79 has suggested using Freefile with "lots of files". I strongly recommend using FreeFile all the time. It's just that it's easy to get into the habit of Open ... as #1 and when you start say, sharing code amongst projects, then you could run into trouble. Also, this way you don't have to track which number to use next and you can use sensible indentifier names for the file channels.

   Dim EmployeeFile as Integer
   EmployeeFile = FreeFile()
   Open ... For Input As #EmployeeFile
   ...
   Close #EmployeeFile

Not a rule, just a suggestion! :-)

(Note you can't use the # with the EOF function. It's EOF(EmployeeFile) as correctly written by vinnyd79).
0
 
LVL 44

Expert Comment

by:Arthur_Wood
ID: 7177252
be aware the Open ... for OUTPUT will wipeout an exiting instance of the named file, before creating a NEW file of that name.  If you want to keep any exiting file, and be able to append to it,  then use Open... FOR APPEND

that will create a NEW file if the named file DOES NOT ALREADY exit, but will open an exiting file of that name, and allow your code to add records onto the end.

Just a note.

Arthur Wood
0
 
LVL 2

Expert Comment

by:selim007
ID: 7177262
//to save data
open "c:\test.txt" for output as #1
print #1,"test line1"
print #1,"test line2"
close #1
//to read all data
open "c:\test.txt" for input as #1
do while not eof(1)
input #1,thechars
list1.additem thechars
doevents
loop
close #1
- you can use the freefile as mentioned above to get the first free file handle
- you can open the file as binary to get binary data
- you can use the put and get method to read data by records.

0
 
LVL 1

Expert Comment

by:prakashbitra
ID: 7178060
I sincerely recommend to use Scripting object for better file management.

  Dim fso, ts
  Set fso = CreateObject("Scripting.FileSystemObject")

  ' where ts is TextStream Object
  Set ts = fso.CreateTextFile(app.path & "\myfile.txt", True)

  ' Write a line with a newline character.
  ts.WriteLine("DATA   A   B  C  D")
  ts.Close

'for reading a  file
  Set ts = fso.OpenTextFile(app.path "\myfile.txt", ForReading)
  do until ts.AtEndofFile
    s = ts.ReadLine
    msgbox s
  loop
  ts.Close

set fso = nothing
0
 
LVL 28

Expert Comment

by:vinnyd79
ID: 7178285
I would sincerely recommend NOT using the scripting object for something that can be done with VB's native I/O functions. Not to mention that you basically proposed an answer that has already been suggested by Damienm.
0
 
LVL 1

Expert Comment

by:kodiakbear
ID: 7522817
Dear prakashbitra
I've rejected your proposed answer as Experts Exchange holds an experiment to work without the answer button.

See: <http://www.experts-exchange.com/jsp/communityNews.jsp>
Paragraph: Site Update for Wednesday, November 06, 2002

By this rejection the Asker will be notified by mail and hopefully he will take his responsibility to finalize the question or post an additional comment.
The Asker sees a button beside every post which says "Accept This Comment As Answer" (including rejected answers) -- so if he/she thinks yours is the best, you'll be awarded the points and the grade.

EXPERTS: I will return in seven days to close this question.
Please leave your thoughts and recommendations here

PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER !

Thanks !

kodiakbear
Experts Exchange Moderator
0
 
LVL 49

Expert Comment

by:DanRollins
ID: 8040620
Hi TheShark8,
It appears that you have forgotten this question. I will ask Community Support to close it unless you finalize it within 7 days. I will ask a Community Support Moderator to:

    Accept vinnyd79's comment(s) as an answer.

TheShark8, if you think your question was not answered at all or if you need help, just post a new comment here; Community Support will help you.  DO NOT accept this comment as an answer.

EXPERTS: If you disagree with that recommendation, please post an explanatory comment.
==========
DanRollins -- EE database cleanup volunteer
0
 

Expert Comment

by:SpideyMod
ID: 8095673
per recommendation

SpideyMod
Community Support Moderator @Experts Exchange
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction While answering a recent question (http://www.experts-exchange.com/Q_27402310.html) in the VB classic zone, I wrote some VB code in the (Office) VBA environment, rather than fire up my older PC.  I didn't post completely correct code o…
You can of course define an array to hold data that is of a particular type like an array of Strings to hold customer names or an array of Doubles to hold customer sales, but what do you do if you want to coordinate that data? This article describes…
As developers, we are not limited to the functions provided by the VBA language. In addition, we can call the functions that are part of the Windows operating system. These functions are part of the Windows API (Application Programming Interface). U…
Get people started with the process of using Access VBA to control Outlook using automation, Microsoft Access can control other applications. An example is the ability to programmatically talk to Microsoft Outlook. Using automation, an Access applic…

687 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