Is there a way to truncate a file? Like this:
Open "Myfile" For Binary As #1
LOF(1) = &h2000
Close #1
Truncate a file
-
- Posts: 862
- Joined: May 05, 2015 5:35
- Location: Germany
Re: Truncate a file
It's a little more complicated, but still quite easy:
Alternatively, if the file isn't too big, you can use a string as buffer:Dim As String filename = "myfile"
Dim As String tempfile = "temp"
Open filename For Binary As #1
Open tempfile For Output As #2
Print #2, Input(1024, #1);
Close
Kill filename
Name(tempfile, filename)
Code: Select all
Dim As String filename = "myfile"
Dim As String buffer
Open filename For Binary As #1
buffer = Input(1024, #1)
Close #1
Open filename For Output As #1
Print #1, buffer;
Close #1
Re: Truncate a file
Code: Select all
Dim As String filename = "myfile"
Dim As String s
Open filename For Binary Access Read As #1
s = Input(1024, #1)
Close #1
Open filename For Output As #1
Print #1, s;
s = ""
Close #1
[edit]
Post cancelled due to code duplication with the above alternative.
Last edited by fxm on Aug 02, 2018 10:48, edited 2 times in total.
Re: Truncate a file
Yes, I did it on that way, with a temp file or a temp string.
I hoped there was a way to do it with 1 move.
Thanks.
I hoped there was a way to do it with 1 move.
Thanks.
Re: Truncate a file
There's such a function in the CRT, which you can use (and is included in every FB binary anyway, so doesn't cause any bloat or additional dependencies). See ftruncate (or chsize on windows).
See also https://freebasic.net/forum/viewtopic.p ... 27&p=47265
See also https://freebasic.net/forum/viewtopic.p ... 27&p=47265
Re: Truncate a file
Very interesting, I go at work with it.
Re: Truncate a file
To keep truncicated file data,looks like you should use "a" -- append.
Code: Select all
#include "file.bi"
#include "crt.bi"
Sub save(filename As String,text As String)
Var f=fopen(filename,"w")
fprintf(f,"%s",text)
fclose(f)
End Sub
Sub truncicate(filename As String,l As Long)
Var f=fopen(filename,"a") '<--------- append
Var handle=_fileno( f )
_chsize(handle,l)
fclose(f)
End Sub
Dim As String f="abcdefghijklmnopqrstuvwxyz"
f+=Ucase(f)+Chr(13,10)
f+=f
f+=f
f=rtrim(f,Chr(13,10))'take off chr(13,10)
'===========
save("test",f)
Print Filelen("test")
Shell "type test"
Print
truncicate("test",58)
Print Filelen("test")
Shell "type test"
Print
truncicate("test",5)
Print Filelen("test")
Shell "type test"
print
Sleep
Re: Truncate a file
It's very nice. Thanks.