Solved

Simple Q - How to create a file

Posted on 2002-07-25
11
150 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
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
 
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
Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

 
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

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

Suggested Solutions

Introduction While answering a recent question about filtering a custom class collection, I realized that this could be accomplished with very little code by using the ScriptControl (SC) library.  This article will introduce you to the SC library a…
Since upgrading to Office 2013 or higher installing the Smart Indenter addin will fail. This article will explain how to install it so it will work regardless of the Office version installed.
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…
Get people started with the utilization of class modules. Class modules can be a powerful tool in Microsoft Access. They allow you to create self-contained objects that encapsulate functionality. They can easily hide the complexity of a process from…

708 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

16 Experts available now in Live!

Get 1:1 Help Now