writing a batch file

Posted on 2000-02-28
Last Modified: 2012-08-14
having trouble opening a file for output
and writing batch file commands, because
of character text formatting problems.
( i think it always adds a carraige
return or line feed to the last line )

how do i get around this so no extra
text formatting characters are added?

Question by:mwam
  • 3
  • 3
  • 2
  • +4

Expert Comment

ID: 2567519
Could you post your existing code so we can check it out?

Expert Comment

ID: 2567543

If you are using the Print statement then it will always append a vbCRLF to the string being added to the file.

With the following code you can preformat a string to the file contents you desire and then write it to the file. Note you may have to delete the previous file with a "KILL" command before calling this routine.

Public Function WriteFile(pstrFileName As String, pstrData As String) As Boolean
    Dim intFile As Integer

    intFile = FreeFile

    Open pstrFileName For Binary Access Write As #intFile
    Put #intFile, 1, pstrData

    If Err.Number <> 0 Then
        WriteFile = True  ' An error condition
        Resume WRITEFILE_ERR1
    End If
    On Error Resume Next

    Close intFile
End Function

Hope this helps

Expert Comment

ID: 2568141
I think that adding a ; to the end of the print line will stop the carriage return.

Print #1, "This"
Print #1, "That"

--Start File--

---End File---

Print #1, "This"
Print #1, "That";

--Start File--
---End File---

Hope this helps!
Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.


Expert Comment

ID: 2568484
In fact, batch files NEED <CR><LF> terminators to recognize each separate line of commands.

Each time you execute the PRINT command, it adds a line separator (the combination of <CR> and <LF>, in that order), EXCEPT when that PRINT command ends with a semicolon.

KDivad's comment is right, but if you try to read a so-generated text file (as a batch command file is) with some older Basic programs, the last line, as it has *NO* line terminator, won't be properly read, because the last "t" (of "That") is not followed by a line terminator; as <EOF> is only there, program will fail to recognise the line, and perhaps:
a) a premature EOF condition may be detected
b) the program hangs at INPUT instruction

Expert Comment

ID: 2569247
I think using filesystemobject are much better than open for output etc.

Set fs = CreateObject("Scripting.FileSystemObject")
Set a = fs.CreateTextFile(App.Path & "\test.txt", True)

a.WriteLine "Testing"
a.WriteLine "123"
end sub

There is more code for append, extract etc.

Expert Comment

ID: 2570289
>>I think using filesystemobject are much better than open for output etc

¿Could you tell me please why? Just only for to satisfy my curiosity...

Author Comment

ID: 2571302
while ed's answer may work...kdavid's
answer is much better. damienm's answer
didn't have any effect. now i'm confused, tho, cause the lack of the
final <CR><LF> wasn't the answer to my
batch file woes. here's what i'm trying
to do: make a bat file that runs dos
ftp and reads from a text file. here's
the code:
Private Sub Command2_Click()
On Error Resume Next

Dim wrap As String
Kill "c:\windows\temp\ftpbatch.bat"
Kill "c:\windows\temp\ftpget.txt"

wrap = Chr(13) & Chr(10)
scriptline = "open " & ftpsite & " " & ftpport & wrap & username & wrap & password & wrap & "binary" & wrap & "lcd temp"

Open "c:\windows\temp\ftpget.txt" For Output As #1
Print #1, scriptline
Print #1, "dir * dir.txt";
Close #1

Open "c:\windows\temp\ftpbatch.bat" For Output As #1
Print #1, "ftp -s:c:\windows\temp\ftpget.txt";
Close #1
Debug.Print scriptline

End Sub

not sure how that will work with the small input text box here on this webpage. the idea is to make a one line
textfile called "ftpget.txt" and a have
the batch file read from that. the batch file works, actually, but gives errors: "parameter value not in allowed
"bad command or filename"
it also does the "dir * dir.txt" command
twice. the batch file actually works,
would just like to understand why it's acting funny and would like to clean it

thanks, mike
LVL 14

Expert Comment

ID: 2571513
mwam.. Your VB code is just fine.. (although you really should consider Option Explicit declarations.. <wink>).
Both the Batch file and the Scriptfile are being written fine.. <smile>.

The problem you are having is the actual script you are passing to FTP.
Right now, it reads..

open ftpsite ftpport
lcd temp
dir * dir.txt

and even without knowing what DOS FTP Script should look like.. this looks very fishy. Positional line delineation for username and password parameters? ... I don't think so !!!

Anyhow.. let me go and research what the script file contents should be. In the meantime, I suggest that you MANUALLY create a script and BAT file, and test it.. after you get something that works.. then adjust your code accordingly.. <smile>.

Once again, there is NOTHING wrong with your program.
LVL 14

Accepted Solution

wsh2 earned 50 total points
ID: 2571666
<drum roll>.. TADA.. This BABY works !!!! The only change I made was a cosmetic one (using vbCrLf rather than wrap).

The FTP.EXE Tool is VERY sensitive.. one error in your script and KABOOM.. invalid commands out the Kazoo !!! Commands are case sensitive (lower), and you MUST relationally follow any server request with the CORRECT response (my apologies for my earlier username, password comment.. <sheesh>).. or your whole stinking script abends. Anyhow.. copy and paste the following.. and then you can change it as you see fit.. <smile>.

Oh.. one other note.. The MS knowledge base has one or two reports on FTP.EXE.. whether they apply to you or not who knows?.. But, you may want to check then out. Type in FTP.EXE as your search.

<--------- Code ------------>

On Error Resume Next

Dim strFtpSite As String
Dim strFtpPort As String
Dim strPassword As String
Dim strScriptLine As String
Dim strUserName As String

strFtpPort = "21"
strFtpSite = ""
strUserName = "anonymous"
strPassword = ""

Kill "c:\windows\temp\ftpbatch.bat"
Kill "c:\windows\temp\ftpget.txt"

strScriptLine = "open " & strFtpSite & " " & strFtpPort & vbCrLf _
    & strUserName & vbCrLf _
    & strPassword & vbCrLf _
    & "binary" & vbCrLf _
    & "lcd c:\windows\temp"

Open "c:\windows\temp\ftpget.txt" For Output As #1
Print #1, strScriptLine
Print #1, "dir * dir.txt";
Close #1

Open "c:\windows\temp\ftpbatch.bat" For Output As #1
Print #1, "ftp -s:c:\windows\temp\ftpget.txt";
Close #1

Debug.Print strScriptLine

Shell "c:\windows\temp\ftpbatch.bat", vbNormalFocus


Expert Comment

ID: 2572059
To Viking

I think it is better because it does not need chr(13) chr(10) etc.

I think it reads code better also, sometimes when I am trying to read only 1 line from a text file using batch code it reads the whole document instead of just 1 line at a time.

Expert Comment

ID: 2572324
>>I think it is better because it does not need chr(13) chr(10) etc.

Note that when you work with Print (even with Write) statements, you disregard of the use of CHR(13/10) (althoug both instructions add the proper line terminator, even when you don't specify it [but Write has NO WAY to disable it]).

Now, provided that WriteLine method acomplishes THE SAME job (to add a line with its own line terminator), ¿where is the difference?


Author Comment

ID: 2572474
used wsh2's exactly the
same results. yes it works, but
getting a couple error msgs and
mysteriously preforms the:
"dir * dir.txt" command twice.
closing the question...thanks
to all who commented :)

mike w
LVL 14

Expert Comment

ID: 2572862
mwan.. On the dir * dir.txt problem, are you sure the server isn't just echoing the command back? If it isn't, as that is the last line you put into the buffer, it doesn't surprise me that FTP.EXE could send it twice (perhaps as a result of inactivity). Don't forget to add FTP.EXE "close", "disconnect" and/or "bye" statements to the end of your script as appropriate, so that you cleanly exit the session.

Another thought.. add a kill on the dir.txt file in the beginning of the procedure. When the FTP.EXE bat finishes, you can then existence test for the dir.txt file to see if the BAT completed.

As stated earlier.. FTP.EXE is VERY finnicky.. the smallest mistake.. and you are off to never never land. Your efforts may be better served by doing a WIN FTP application.. where you can intercept FTP server responses and take appropriate action.. <smile>.


Featured Post

ScreenConnect 6.0 Free Trial

Explore all the enhancements in one game-changing release, ScreenConnect 6.0, based on partner feedback. New features include a redesigned UI, app configurations and chat acknowledgement to improve customer engagement!

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
VBS file using code from 2nd file (txt or vbs) 4 36
bit defender blocks good applications 2 94
vb6 connector to mongodb 2 83
how to Classify of email (pdf attachments) 7 36
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…
Have you ever wanted to restrict the users input in a textbox to numbers, and while doing that make sure that they can't 'cheat' by pasting in non-numeric text? Of course you can do that with code you write yourself but it's tedious and error-prone …
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…
This lesson covers basic error handling code in Microsoft Excel using VBA. This is the first lesson in a 3-part series that uses code to loop through an Excel spreadsheet in VBA and then fix errors, taking advantage of error handling code. This l…

770 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