How to over write a text file(Not add to end of text file)?
Hi all. I am using the following lines to write to a text file. The current code keeps adding data to the end of text file!! But i want this code to over right the text file(Not add data to end of the text file) with fresh data and if the text file didn't exist create one.
3 Code:
Open "C:\data.txt" For Append As #1
Print #1, strUser; " ID:"; strId
Close #1
Re: How to over right a text file(Not add to end of text file)?
Why don't you just delete the file first?
Code:
Kill "C:\data.txt"
Open "C:\data.txt" For Append As #1
Re: How to over right a text file(Not add to end of text file)?
Quote:
Originally Posted by dee-u
Why don't you just delete the file first?
Code:
Kill "C:\data.txt"
Open "C:\data.txt" For Append As #1
Thanks for your reply. But what will happen if the file doesn't exit ? Does it create one or gives error ?
Re: How to over right a text file(Not add to end of text file)?
try:
Code:
Open "C:\data.txt" For output As #1
Print #1, strUser; " ID:"; strId
Close #1
Re: How to over right a text file(Not add to end of text file)?
There is the 'Check file existence' link in my sig, you can do that before deleting it.
Re: How to over right a text file(Not add to end of text file)?
Quote:
Originally Posted by jp26198926
try:
Code:
Open "C:\data.txt" For output As #1
Print #1, strUser; " ID:"; strId
Close #1
I trie your code but actually this is not what i want.(your code only writes the last data from the loop only!!) My code is running on load event and is inside a loop .But i want the file be erased the next the form gets loaded!!!
Re: How to over right a text file(Not add to end of text file)?
Could you also try this function?
Code:
Private Sub clearFile(ByVal strPath As String)
If Not Len(Dir(strPath)) = 0 Then
Open strPath For Output As #1
Close #1
End If
End Sub
Re: How to over right a text file(Not add to end of text file)?
try this:
Code:
fname = "C:\YourFile.txt"
If FileExists(fname)
kill fname
end if
Open fname For Output As #fNumber
For i = 0 To List1.ListCount - 1
If List1.list(i) <> "" Then
Print #fNumber, List1.list(i)
End If
Next
Close #fNumber
Open fname For Input As #fNumber
Do While Not EOF(fNumber)
Line Input #fNumber, sItem
If sItem <> "" Then
List1.AddItem sItem
End If
Loop
Close #fNumber
Function FileExists(FileName As String) As Boolean
On Error GoTo ErrorHandler
' get the attributes and ensure that it isn't a directory
FileExists = (GetAttr(FileName) And vbDirectory) = 0
Exit Function
ErrorHandler:
'MsgBox "File does not exist"
' if an error occurs, this function returns False
End Function
Re: How to over right a text file(Not add to end of text file)?
If you know you want to throw a file away and replace it if present, it can be just as easy to use:
Code:
On Error Resume Next: Kill filename: On Error GoTo 0
If you are using unstructured error handling in this routine change GoTo 0 to GoTo line/label. But For Output should already take care of it in your case.