Truncate a file: Difference between revisions

Content added Content deleted
(Added XPL0 example.)
m (syntax highlighting fixup automation)
Line 18: Line 18:
{{trans|Python}}
{{trans|Python}}


<lang 11l>F truncate_file(name, length)
<syntaxhighlight lang="11l">F truncate_file(name, length)
I !fs:is_file(name)
I !fs:is_file(name)
R 0B
R 0B
Line 24: Line 24:
R 0B
R 0B
fs:resize_file(name, length)
fs:resize_file(name, length)
R 1B</lang>
R 1B</syntaxhighlight>


=={{header|Action!}}==
=={{header|Action!}}==
The attached result has been obtained under DOS 2.5.
The attached result has been obtained under DOS 2.5.
{{libheader|Action! Tool Kit}}
{{libheader|Action! Tool Kit}}
<lang Action!>INCLUDE "D2:IO.ACT" ;from the Action! Tool Kit
<syntaxhighlight lang="action!">INCLUDE "D2:IO.ACT" ;from the Action! Tool Kit


PROC Dir(CHAR ARRAY filter)
PROC Dir(CHAR ARRAY filter)
Line 130: Line 130:
PrintF("Dir ""%S""%E",filter)
PrintF("Dir ""%S""%E",filter)
Dir(filter)
Dir(filter)
RETURN</lang>
RETURN</syntaxhighlight>
{{out}}
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Truncate_a_file.png Screenshot from Atari 8-bit computer]
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Truncate_a_file.png Screenshot from Atari 8-bit computer]
Line 153: Line 153:
The following program is an implementation in Ada using system-independent tools from the standard library to read and write files, remove and rename them. It should work for on any system with byte-oriented file storage and uses Ada 2012 conditional expressions.
The following program is an implementation in Ada using system-independent tools from the standard library to read and write files, remove and rename them. It should work for on any system with byte-oriented file storage and uses Ada 2012 conditional expressions.


<lang Ada>with Ada.Command_Line, Ada.Sequential_IO, Ada.Directories;
<syntaxhighlight lang="ada">with Ada.Command_Line, Ada.Sequential_IO, Ada.Directories;


procedure Truncate_File is
procedure Truncate_File is
Line 207: Line 207:
end if;
end if;
end;
end;
end Truncate_File;</lang>
end Truncate_File;</syntaxhighlight>


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<lang autohotkey>truncFile("S:\Portables\AutoHotkey\My Scripts\Other_Codes\motion2.ahk", 1200)
<syntaxhighlight lang="autohotkey">truncFile("S:\Portables\AutoHotkey\My Scripts\Other_Codes\motion2.ahk", 1200)
return
return


Line 222: Line 222:
f.length := length_bytes
f.length := length_bytes
f.close()
f.close()
}</lang>
}</syntaxhighlight>


=={{header|AWK}}==
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f TRUNCATE_A_FILE.AWK
# syntax: GAWK -f TRUNCATE_A_FILE.AWK
BEGIN {
BEGIN {
Line 271: Line 271:
return(msg)
return(msg)
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 285: Line 285:
This is fairly generic MS BASIC. As such, it actually works in a wide variety of compilers and interpreters -- certainly too many to list here, but the list includes non-.Net [[Visual Basic]], [[FreeBASIC]], [[QB64]], etc. With a user-provided implementation of <code>DIR$</code>, it even works under [[QBasic]].
This is fairly generic MS BASIC. As such, it actually works in a wide variety of compilers and interpreters -- certainly too many to list here, but the list includes non-.Net [[Visual Basic]], [[FreeBASIC]], [[QB64]], etc. With a user-provided implementation of <code>DIR$</code>, it even works under [[QBasic]].


<lang qbasic>SUB truncateFile (file AS STRING, length AS LONG)
<syntaxhighlight lang="qbasic">SUB truncateFile (file AS STRING, length AS LONG)
IF LEN(DIR$(file)) THEN
IF LEN(DIR$(file)) THEN
DIM f AS LONG, c AS STRING
DIM f AS LONG, c AS STRING
Line 304: Line 304:
ERROR 53
ERROR 53
END IF
END IF
END SUB</lang>
END SUB</syntaxhighlight>


See also: [[#FreeBASIC|FreeBASIC]], [[#Liberty BASIC|Liberty BASIC]], [[#PowerBASIC|PowerBASIC]], [[#PureBasic|PureBasic]], [[#ZX Spectrum Basic|ZX Spectrum Basic]].
See also: [[#FreeBASIC|FreeBASIC]], [[#Liberty BASIC|Liberty BASIC]], [[#PowerBASIC|PowerBASIC]], [[#PureBasic|PureBasic]], [[#ZX Spectrum Basic|ZX Spectrum Basic]].
Line 310: Line 310:
=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
This will extend the file if the specified length is greater than the existing length. A test to prevent that could easily be added.
This will extend the file if the specified length is greater than the existing length. A test to prevent that could easily be added.
<lang bbcbasic> DEF PROCtruncate(file$, size%)
<syntaxhighlight lang="bbcbasic"> DEF PROCtruncate(file$, size%)
LOCAL file%
LOCAL file%
file% = OPENUP(file$)
file% = OPENUP(file$)
Line 316: Line 316:
EXT#file% = size%
EXT#file% = size%
CLOSE #file%
CLOSE #file%
ENDPROC</lang>
ENDPROC</syntaxhighlight>


=={{header|Bracmat}}==
=={{header|Bracmat}}==
Handling binary data is not easy in Bracmat. This solution reads all bytes as numbers. They are prepended to a list. After reversing the list, all numbers are written to the file. Notice that to close a file you should try to seek to a non-existing file position.<code>fil$(,SET,-1)</code> seeks to the position before the start of the file currently in focus.
Handling binary data is not easy in Bracmat. This solution reads all bytes as numbers. They are prepended to a list. After reversing the list, all numbers are written to the file. Notice that to close a file you should try to seek to a non-existing file position.<code>fil$(,SET,-1)</code> seeks to the position before the start of the file currently in focus.
<lang bracmat>( ( trunc
<syntaxhighlight lang="bracmat">( ( trunc
= name length elif file c
= name length elif file c
. !arg:(?name,?length)
. !arg:(?name,?length)
Line 342: Line 342:
| out$"File too short"
| out$"File too short"
)
)
);</lang>
);</syntaxhighlight>
Output:
Output:
<pre>I have a secret to t</pre>
<pre>I have a secret to t</pre>
Line 355: Line 355:


{{works with|MinGW}}
{{works with|MinGW}}
<lang c>#include <windows.h>
<syntaxhighlight lang="c">#include <windows.h>
#include <stdio.h>
#include <stdio.h>
#include <wchar.h>
#include <wchar.h>
Line 435: Line 435:


return dotruncate(fn, fp);
return dotruncate(fn, fp);
}</lang>
}</syntaxhighlight>


===POSIX===
===POSIX===
<lang c>#include <unistd.h>
<syntaxhighlight lang="c">#include <unistd.h>
#include <sys/types.h>
#include <sys/types.h>


Line 445: Line 445:
ftruncate(fd, length);
ftruncate(fd, length);
...
...
</syntaxhighlight>
</lang>
Both functions have <code>length</code> argument of <code>off_t</code> type. There are about a million possible errors, of interest to this task are <code>EFBIG</code>: size too large; <code>EINVAL</code>: size is negative or too large; <code>EIO</code>: IO error; <code>EACCESS</code> (for <code>truncate</code>): either can't see or can't write to the file; <code>EBADF</code> or <code>EINVAL</code> (for <code>ftruncate</code>): file descriptor is not a file descriptor, or not opened for writing.
Both functions have <code>length</code> argument of <code>off_t</code> type. There are about a million possible errors, of interest to this task are <code>EFBIG</code>: size too large; <code>EINVAL</code>: size is negative or too large; <code>EIO</code>: IO error; <code>EACCESS</code> (for <code>truncate</code>): either can't see or can't write to the file; <code>EBADF</code> or <code>EINVAL</code> (for <code>ftruncate</code>): file descriptor is not a file descriptor, or not opened for writing.


Line 452: Line 452:
=={{header|C sharp}}==
=={{header|C sharp}}==


<lang c sharp>using System;
<syntaxhighlight lang="c sharp">using System;
using System.IO;
using System.IO;


Line 479: Line 479:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|C++}}==
=={{header|C++}}==
<lang C++>#include <string>
<syntaxhighlight lang="c++">#include <string>
#include <fstream>
#include <fstream>


Line 502: Line 502:
return 0;
return 0;
}
}
</syntaxhighlight>
</lang>


=={{header|Clojure}}==
=={{header|Clojure}}==
{{trans|Java}}
{{trans|Java}}
<lang clojure>(defn truncate [file size]
<syntaxhighlight lang="clojure">(defn truncate [file size]
(with-open [chan (.getChannel (java.io.FileOutputStream. file true))]
(with-open [chan (.getChannel (java.io.FileOutputStream. file true))]
(.truncate chan size)))
(.truncate chan size)))


(truncate "truncate_test.txt" 2)</lang>
(truncate "truncate_test.txt" 2)</syntaxhighlight>


=={{header|D}}==
=={{header|D}}==
<lang d>import std.file, std.exception;
<syntaxhighlight lang="d">import std.file, std.exception;


void truncateFile(in string name, in size_t newSize) {
void truncateFile(in string name, in size_t newSize) {
Line 534: Line 534:
void main() {
void main() {
truncateFile("truncate_test.txt", 0);
truncateFile("truncate_test.txt", 0);
}</lang>
}</syntaxhighlight>


=={{header|Delphi}}==
=={{header|Delphi}}==
Line 540: Line 540:
Delphi has the same <code>truncate</code> method as Pascal, which could be used like this:
Delphi has the same <code>truncate</code> method as Pascal, which could be used like this:


<lang Delphi>procedure TruncateFile(FileName : string; NewSize : integer);
<syntaxhighlight lang="delphi">procedure TruncateFile(FileName : string; NewSize : integer);
var
var
aFile: file of byte;
aFile: file of byte;
Line 552: Line 552:
Close(afile);
Close(afile);
end;
end;
end;</lang>
end;</syntaxhighlight>


Most people nowadays seem to use streams to access files, so an alternative is:
Most people nowadays seem to use streams to access files, so an alternative is:


<lang Delphi>procedure TruncateFile(FileName : string; NewSize : integer);
<syntaxhighlight lang="delphi">procedure TruncateFile(FileName : string; NewSize : integer);
var
var
Stream : TFileStream;
Stream : TFileStream;
Line 566: Line 566:
Stream.Free;
Stream.Free;
end;
end;
end;</lang>
end;</syntaxhighlight>


With both of these approaches, if the NewSize is greater than the existing file size the file will be expanded and filled with nulls.
With both of these approaches, if the NewSize is greater than the existing file size the file will be expanded and filled with nulls.
Line 579: Line 579:
=={{header|Elena}}==
=={{header|Elena}}==
ELENA 4.x:
ELENA 4.x:
<lang elena>import system'io;
<syntaxhighlight lang="elena">import system'io;
import extensions;
import extensions;
Line 606: Line 606:
file.Length := length
file.Length := length
}</lang>
}</syntaxhighlight>


=={{header|Erlang}}==
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
<lang Erlang>
-module( truncate ).
-module( truncate ).


Line 621: Line 621:
{ok, Size} = file:position( IO, {bof, Size} ),
{ok, Size} = file:position( IO, {bof, Size} ),
ok = file:truncate( IO ).
ok = file:truncate( IO ).
</syntaxhighlight>
</lang>


=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
{{trans|C#}}
{{trans|C#}}
<lang fsharp>open System
<syntaxhighlight lang="fsharp">open System
open System.IO
open System.IO


Line 637: Line 637:
let main args =
let main args =
truncateFile args.[0] (Int64.Parse(args.[1]))
truncateFile args.[0] (Int64.Parse(args.[1]))
0</lang>
0</syntaxhighlight>


=={{header|Fortran}}==
=={{header|Fortran}}==
Line 653: Line 653:
There is an option to specify BUFFERED="YES" and BUFFERCOUNT=n or similar in many Fortrans, but alas, these are not standard even in F90/95. One's guilt is not so easily diverted, but, ... this is really only a demonstration, perhaps with very occasional use.
There is an option to specify BUFFERED="YES" and BUFFERCOUNT=n or similar in many Fortrans, but alas, these are not standard even in F90/95. One's guilt is not so easily diverted, but, ... this is really only a demonstration, perhaps with very occasional use.


And so...<lang Fortran> SUBROUTINE CROAK(GASP) !Something bad has happened.
And so...<syntaxhighlight lang="fortran"> SUBROUTINE CROAK(GASP) !Something bad has happened.
CHARACTER*(*) GASP !As noted.
CHARACTER*(*) GASP !As noted.
WRITE (6,*) "Oh dear. ",GASP !So, gasp away.
WRITE (6,*) "Oh dear. ",GASP !So, gasp away.
Line 698: Line 698:
PROGRAM CHOPPER
PROGRAM CHOPPER
CALL FILEHACK("foobar.txt",12)
CALL FILEHACK("foobar.txt",12)
END</lang>
END</syntaxhighlight>




=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
{{trans|QuickBASIC}}
{{trans|QuickBASIC}}
<lang freebasic>Sub truncateFile (archivo As String, longitud As Long)
<syntaxhighlight lang="freebasic">Sub truncateFile (archivo As String, longitud As Long)
If Len(Dir(archivo)) Then
If Len(Dir(archivo)) Then
Dim f As Long, c As String
Dim f As Long, c As String
Line 722: Line 722:
Error 53 'File not found
Error 53 'File not found
End If
End If
End Sub</lang>
End Sub</syntaxhighlight>


=={{header|Go}}==
=={{header|Go}}==
Go has the required function in the standard library. The implementation calls operating system specific functions and returns whatever errors the operating system reports.
Go has the required function in the standard library. The implementation calls operating system specific functions and returns whatever errors the operating system reports.
<lang go>import (
<syntaxhighlight lang="go">import (
"fmt"
"fmt"
"os"
"os"
Line 733: Line 733:
if err := os.Truncate("filename", newSize); err != nil {
if err := os.Truncate("filename", newSize); err != nil {
fmt.Println(err)
fmt.Println(err)
}</lang>
}</syntaxhighlight>
Package os also has a separate function that operates on an open file.
Package os also has a separate function that operates on an open file.


Line 739: Line 739:
This can be achieved by using the <code>setFileSize</code> function in [http://hackage.haskell.org/packages/archive/unix-compat/0.1.2.1/doc/html/System-PosixCompat-Files.html#13 System.PosixCompat.Files]:
This can be achieved by using the <code>setFileSize</code> function in [http://hackage.haskell.org/packages/archive/unix-compat/0.1.2.1/doc/html/System-PosixCompat-Files.html#13 System.PosixCompat.Files]:


<lang Haskell>setFileSize :: FilePath -> FileOffset -> IO ()
<syntaxhighlight lang="haskell">setFileSize :: FilePath -> FileOffset -> IO ()
-- Truncates the file down to the specified length.
-- Truncates the file down to the specified length.
-- If the file was larger than the given length
-- If the file was larger than the given length
-- before this operation was performed the extra is lost.
-- before this operation was performed the extra is lost.
-- Note: calls truncate.
-- Note: calls truncate.
</syntaxhighlight>
</lang>


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
Unicon provides the built-in function truncate which can be used to truncate a file. The following line of code truncates ''filename'' to ''newsizeinbytes''. The file is opened for both read and write in untranslated mode.
Unicon provides the built-in function truncate which can be used to truncate a file. The following line of code truncates ''filename'' to ''newsizeinbytes''. The file is opened for both read and write in untranslated mode.
<lang Unicon>truncate(f := open(filename, "bu"), newsizeinbytes) & close(f)</lang>
<syntaxhighlight lang="unicon">truncate(f := open(filename, "bu"), newsizeinbytes) & close(f)</syntaxhighlight>
Note: The Unicon book incorrectly indicates that truncate doesn't work on Windows.
Note: The Unicon book incorrectly indicates that truncate doesn't work on Windows.


=={{header|J}}==
=={{header|J}}==
'''Solution:'''
'''Solution:'''
<lang j>require 'files' NB. needed for versions prior to J7
<syntaxhighlight lang="j">require 'files' NB. needed for versions prior to J7
ftruncate=: ] fwrite~ ] fread@; 0 , [</lang>
ftruncate=: ] fwrite~ ] fread@; 0 , [</syntaxhighlight>
'''Usage:'''
'''Usage:'''
<lang j> (1000$ 'abcdefg') fwrite 'text.txt' NB. create test file
<syntaxhighlight lang="j"> (1000$ 'abcdefg') fwrite 'text.txt' NB. create test file
567 ftruncate 'test.txt' NB. truncate test file
567 ftruncate 'test.txt' NB. truncate test file
567
567
fsize 'test.txt' NB. check new file size
fsize 'test.txt' NB. check new file size
567</lang>
567</syntaxhighlight>


=={{header|Java}}==
=={{header|Java}}==
The built-in function for truncating a file in Java will leave the file unchanged if the specified size is larger than the file. This version expects the source file name and the new size as command line arguments (in that order).
The built-in function for truncating a file in Java will leave the file unchanged if the specified size is larger than the file. This version expects the source file name and the new size as command line arguments (in that order).
<lang java>import java.io.FileOutputStream;
<syntaxhighlight lang="java">import java.io.FileOutputStream;
import java.io.IOException;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel;
Line 780: Line 780:
outChan.close();
outChan.close();
}
}
}</lang>
}</syntaxhighlight>


=={{header|Julia}}==
=={{header|Julia}}==
Uses the built-in <code>truncate</code> function (which truncates a stream):
Uses the built-in <code>truncate</code> function (which truncates a stream):
<lang julia>function truncate_file(fname, size):
<syntaxhighlight lang="julia">function truncate_file(fname, size):
open(fname, "r+") do f
open(fname, "r+") do f
truncate(f, size)
truncate(f, size)
end
end
end</lang>
end</syntaxhighlight>


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>// version 1.1.2
<syntaxhighlight lang="scala">// version 1.1.2


import java.io.FileOutputStream
import java.io.FileOutputStream
Line 815: Line 815:
fun main(args: Array<String>) {
fun main(args: Array<String>) {
truncateFile("test.txt", 10)
truncateFile("test.txt", 10)
}</lang>
}</syntaxhighlight>


=={{header|Lasso}}==
=={{header|Lasso}}==
<lang Lasso>define file_truncate(path::string, size::integer) => {
<syntaxhighlight lang="lasso">define file_truncate(path::string, size::integer) => {


local(file = file(#path))
local(file = file(#path))
Line 836: Line 836:


stdoutnl(file(#filepath) -> readbytes)
stdoutnl(file(#filepath) -> readbytes)
stdout(file('Truncated size: ' + #filepath) -> size)</lang>
stdout(file('Truncated size: ' + #filepath) -> size)</syntaxhighlight>
Output:
Output:
<pre>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris consequat
<pre>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris consequat
Line 859: Line 859:
<br>
<br>
It is also possible to call API functions to achieve this task.
It is also possible to call API functions to achieve this task.
<syntaxhighlight lang="lb">
<lang lb>
dim info$( 50, 50) ' NB pre-dimension before calling file-exists
dim info$( 50, 50) ' NB pre-dimension before calling file-exists
' needed for file-exists function
' needed for file-exists function
Line 890: Line 890:


end
end
</syntaxhighlight>
</lang>


=={{header|Lingo}}==
=={{header|Lingo}}==
With native means (Fileio Xtra) file truncation can only be implemented indirectly, either using a temp file or loading truncated file contents into memory, deleting original and writing memory back to file:
With native means (Fileio Xtra) file truncation can only be implemented indirectly, either using a temp file or loading truncated file contents into memory, deleting original and writing memory back to file:
<lang lingo>----------------------------------------
<syntaxhighlight lang="lingo">----------------------------------------
-- Truncates file
-- Truncates file
-- @param {string} filename
-- @param {string} filename
Line 921: Line 921:
fp.closeFile()
fp.closeFile()
return ok
return ok
end</lang>
end</syntaxhighlight>
But there are also free plugins ("Xtras") like e.g. "BinFile Xtra" that support "in-file" truncation:
But there are also free plugins ("Xtras") like e.g. "BinFile Xtra" that support "in-file" truncation:
{{libheader|BinFile Xtra}}
{{libheader|BinFile Xtra}}
<lang lingo>-- truncates file to 10 KB length
<syntaxhighlight lang="lingo">-- truncates file to 10 KB length
bx_file_truncate(_movie.path&"foo.dat", 10240)</lang>
bx_file_truncate(_movie.path&"foo.dat", 10240)</syntaxhighlight>


=={{header|Lua}}==
=={{header|Lua}}==
Lua treats strings as being invariably one byte per character (hence the awkwardness of trying to use it with unicode), so it's safe to use string methods to truncate binary data.
Lua treats strings as being invariably one byte per character (hence the awkwardness of trying to use it with unicode), so it's safe to use string methods to truncate binary data.
<lang Lua>function truncate (filename, length)
<syntaxhighlight lang="lua">function truncate (filename, length)
local inFile = io.open(filename, 'r')
local inFile = io.open(filename, 'r')
if not inFile then
if not inFile then
Line 942: Line 942:
outFile:write(wholeFile:sub(1, length))
outFile:write(wholeFile:sub(1, length))
outFile:close()
outFile:close()
end</lang>
end</syntaxhighlight>


=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<lang Mathematica>Truncate[file_, n_] := Module[{filename = file, nbbytes = n, temp},
<syntaxhighlight lang="mathematica">Truncate[file_, n_] := Module[{filename = file, nbbytes = n, temp},
temp = $TemporaryPrefix <> filename;
temp = $TemporaryPrefix <> filename;
BinaryWrite[temp, BinaryReadList[filename, "Byte", nbbytes]];
BinaryWrite[temp, BinaryReadList[filename, "Byte", nbbytes]];
Close[temp]; DeleteFile[filename]; RenameFile[temp, filename];
Close[temp]; DeleteFile[filename]; RenameFile[temp, filename];
]</lang>
]</syntaxhighlight>


=={{header|MATLAB}} / {{header|Octave}}==
=={{header|MATLAB}} / {{header|Octave}}==
<lang MATLAB>function truncate_a_file(fn,count);
<syntaxhighlight lang="matlab">function truncate_a_file(fn,count);


fid=fopen(fn,'r');
fid=fopen(fn,'r');
Line 960: Line 960:
fid=fopen(fn,'w');
fid=fopen(fn,'w');
s = fwrite(fid,s,'uint8');
s = fwrite(fid,s,'uint8');
fclose(fid); </lang>
fclose(fid); </syntaxhighlight>


=={{header|Nim}}==
=={{header|Nim}}==
Line 967: Line 967:
The function returns a code which can be checked to emit a message or raise an exception in case of error. In the following example, we ignore (discard) this return code.
The function returns a code which can be checked to emit a message or raise an exception in case of error. In the following example, we ignore (discard) this return code.


<lang nim>import posix
<syntaxhighlight lang="nim">import posix


discard truncate("filename", 1024)</lang>
discard truncate("filename", 1024)</syntaxhighlight>


=={{header|OCaml}}==
=={{header|OCaml}}==
Line 975: Line 975:
The <code>Unix</code> module provided with the standard distribution provides a function <code>[http://caml.inria.fr/pub/docs/manual-ocaml/libref/Unix.html#VALtruncate truncate]</code>:
The <code>Unix</code> module provided with the standard distribution provides a function <code>[http://caml.inria.fr/pub/docs/manual-ocaml/libref/Unix.html#VALtruncate truncate]</code>:


<lang ocaml>val truncate : string -> int -> unit
<syntaxhighlight lang="ocaml">val truncate : string -> int -> unit
(** Truncates the named file to the given size. *)</lang>
(** Truncates the named file to the given size. *)</syntaxhighlight>


There is also a function <code>[http://caml.inria.fr/pub/docs/manual-ocaml/libref/Unix.html#VALftruncate ftruncate]</code> that does the equivalent operation but with a file descriptor instead of a file name:
There is also a function <code>[http://caml.inria.fr/pub/docs/manual-ocaml/libref/Unix.html#VALftruncate ftruncate]</code> that does the equivalent operation but with a file descriptor instead of a file name:


<lang ocaml>val ftruncate : file_descr -> int -> unit
<syntaxhighlight lang="ocaml">val ftruncate : file_descr -> int -> unit
(** Truncates the file corresponding to the given descriptor to the given size. *)</lang>
(** Truncates the file corresponding to the given descriptor to the given size. *)</syntaxhighlight>


=={{header|PARI/GP}}==
=={{header|PARI/GP}}==


Create a file /tmp/test.file and truncate to 20 bytes: (Linux only)
Create a file /tmp/test.file and truncate to 20 bytes: (Linux only)
<lang parigp>install("truncate", "isL", "trunc")
<syntaxhighlight lang="parigp">install("truncate", "isL", "trunc")


trunc("/tmp/test.file", 20)</lang>
trunc("/tmp/test.file", 20)</syntaxhighlight>


=={{header|Pascal}}==
=={{header|Pascal}}==
<lang pascal>
<syntaxhighlight lang="pascal">
Program FileTruncate;
Program FileTruncate;


Line 1,028: Line 1,028:
writeln('File "', filename, '" truncated at position ', position, '.');
writeln('File "', filename, '" truncated at position ', position, '.');
end.
end.
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 1,037: Line 1,037:


=={{header|Perl}}==
=={{header|Perl}}==
<lang perl># Open a file for writing, and truncate it to 1234 bytes.
<syntaxhighlight lang="perl"># Open a file for writing, and truncate it to 1234 bytes.
open FOO, ">>file" or die;
open FOO, ">>file" or die;
truncate(FOO, 1234);
truncate(FOO, 1234);
Line 1,043: Line 1,043:


# Truncate a file to 567 bytes.
# Truncate a file to 567 bytes.
truncate("file", 567);</lang>
truncate("file", 567);</syntaxhighlight>


=={{header|Phix}}==
=={{header|Phix}}==
In honour of this very task, there is now (0.8.0+) a set_file_size() builtin, for the grubby/cross-platform details see builtins/pfile.e (an autoinclude)<br>
In honour of this very task, there is now (0.8.0+) a set_file_size() builtin, for the grubby/cross-platform details see builtins/pfile.e (an autoinclude)<br>
It will pad or truncate as needed.
It will pad or truncate as needed.
<!--<lang Phix>(notonline)-->
<!--<syntaxhighlight lang="phix">(notonline)-->
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span> <span style="color: #000080;font-style:italic;">-- (file i/o)</span>
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span> <span style="color: #000080;font-style:italic;">-- (file i/o)</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">get_file_size</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"test.txt"</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">get_file_size</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"test.txt"</span><span style="color: #0000FF;">)</span>
Line 1,055: Line 1,055:
<span style="color: #0000FF;">?</span><span style="color: #000000;">set_file_size</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"test.txt"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1024</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">set_file_size</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"test.txt"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1024</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">get_file_size</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"test.txt"</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">get_file_size</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"test.txt"</span><span style="color: #0000FF;">)</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}} (annotated, repeatable, assumes test.txt already exists)
{{out}} (annotated, repeatable, assumes test.txt already exists)
<pre>
<pre>
Line 1,067: Line 1,067:
=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
On the 64-bit version, we can call the native runtime library:
On the 64-bit version, we can call the native runtime library:
<lang PicoLisp>(de truncate (File Len)
<syntaxhighlight lang="picolisp">(de truncate (File Len)
(native "@" "truncate" 'I File Len) )</lang>
(native "@" "truncate" 'I File Len) )</syntaxhighlight>
Otherwise (on all versions), we call the external truncate command:
Otherwise (on all versions), we call the external truncate command:
<lang PicoLisp>(de truncate (File Len)
<syntaxhighlight lang="picolisp">(de truncate (File Len)
(call "truncate" "-s" Len File) )</lang>
(call "truncate" "-s" Len File) )</syntaxhighlight>


=={{header|PL/I}}==
=={{header|PL/I}}==
<lang>
<syntaxhighlight lang="text">
/* Parameters to be read in by the program are: */
/* Parameters to be read in by the program are: */
/* 1. the name of the file to be truncated, and */
/* 1. the name of the file to be truncated, and */
Line 1,103: Line 1,103:
end;
end;
end truncate_file;
end truncate_file;
</syntaxhighlight>
</lang>


=={{header|PowerBASIC}}==
=={{header|PowerBASIC}}==
Line 1,110: Line 1,110:
While PowerBASIC can use the QuickBASIC version of <code>truncateFile</code>, PB provides an easier way to do this, via the <code>SETEOF</code> function -- but since <code>SETEOF</code> will extend a file if it is not as long as specified, we still need to wrap it in a <code>SUB</code> to meet this task's specifications.
While PowerBASIC can use the QuickBASIC version of <code>truncateFile</code>, PB provides an easier way to do this, via the <code>SETEOF</code> function -- but since <code>SETEOF</code> will extend a file if it is not as long as specified, we still need to wrap it in a <code>SUB</code> to meet this task's specifications.


<lang powerbasic>SUB truncateFile (file AS STRING, length AS DWORD)
<syntaxhighlight lang="powerbasic">SUB truncateFile (file AS STRING, length AS DWORD)
IF LEN(DIR$(file)) THEN
IF LEN(DIR$(file)) THEN
DIM f AS LONG
DIM f AS LONG
Line 1,126: Line 1,126:
ERROR 53 'File not found
ERROR 53 'File not found
END IF
END IF
END SUB</lang>
END SUB</syntaxhighlight>


=={{header|Powershell}}==
=={{header|Powershell}}==
<lang powershell>Function Truncate-File(fname) {
<syntaxhighlight lang="powershell">Function Truncate-File(fname) {
$null | Set-Content -Path "$fname"
$null | Set-Content -Path "$fname"
}
}
</syntaxhighlight>
</lang>


=={{header|PureBasic}}==
=={{header|PureBasic}}==
PureBasic has the internal function [http://www.purebasic.com/documentation/file/truncatefile.html TruncateFile] that cuts the file at the current file position and discards all data that follows.
PureBasic has the internal function [http://www.purebasic.com/documentation/file/truncatefile.html TruncateFile] that cuts the file at the current file position and discards all data that follows.
<lang PureBasic>Procedure SetFileSize(File$, length.q)
<syntaxhighlight lang="purebasic">Procedure SetFileSize(File$, length.q)
Protected fh, pos, i
Protected fh, pos, i
If FileSize(File$) < length
If FileSize(File$) < length
Line 1,148: Line 1,148:
EndIf
EndIf
ProcedureReturn #True
ProcedureReturn #True
EndProcedure</lang>
EndProcedure</syntaxhighlight>


=={{header|Python}}==
=={{header|Python}}==
<lang python>
<syntaxhighlight lang="python">
def truncate_file(name, length):
def truncate_file(name, length):
if not os.path.isfile(name):
if not os.path.isfile(name):
Line 1,160: Line 1,160:
f.truncate(length)
f.truncate(length)
return True
return True
</syntaxhighlight>
</lang>


=={{header|R}}==
=={{header|R}}==
<syntaxhighlight lang="r">
<lang R>
truncate_file <- function(filename, n_bytes) {
truncate_file <- function(filename, n_bytes) {
Line 1,192: Line 1,192:
}
}
</syntaxhighlight>
</lang>


=={{header|Racket}}==
=={{header|Racket}}==
Line 1,198: Line 1,198:
Racket has a <tt>file-truncate</tt> function that expects an open port and truncate its associated file. Note that it can also extend the file, and the code below prints a warning in that case.
Racket has a <tt>file-truncate</tt> function that expects an open port and truncate its associated file. Note that it can also extend the file, and the code below prints a warning in that case.


<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
#lang racket


Line 1,206: Line 1,206:
(call-with-output-file* file #:exists 'update
(call-with-output-file* file #:exists 'update
(λ(o) (file-truncate o size))))
(λ(o) (file-truncate o size))))
</syntaxhighlight>
</lang>


=={{header|Raku}}==
=={{header|Raku}}==
(formerly Perl 6)
(formerly Perl 6)
{{Works with|rakudo|2016.07}}
{{Works with|rakudo|2016.07}}
<lang perl6>use NativeCall;
<syntaxhighlight lang="raku" line>use NativeCall;


sub truncate(Str, int32 --> int32) is native {*}
sub truncate(Str, int32 --> int32) is native {*}
Line 1,222: Line 1,222:
}
}
truncate($file, $to) == 0 or die "Truncation was unsuccessful";
truncate($file, $to) == 0 or die "Truncation was unsuccessful";
}</lang>
}</syntaxhighlight>


The external <code>truncate</code> routine could be replaced with the following line (in which case no need for <code>NativeCall</code>):
The external <code>truncate</code> routine could be replaced with the following line (in which case no need for <code>NativeCall</code>):
<lang perl6>spurt $file, slurp($file).substr($to);</lang>
<syntaxhighlight lang="raku" line>spurt $file, slurp($file).substr($to);</syntaxhighlight>


=={{header|REXX}}==
=={{header|REXX}}==
Line 1,236: Line 1,236:
::::* &nbsp; then erased (deleted),
::::* &nbsp; then erased (deleted),
::::* &nbsp; then written to.
::::* &nbsp; then written to.
<lang rexx>/*REXX program truncates a file to a specified (and smaller) number of bytes. */
<syntaxhighlight lang="rexx">/*REXX program truncates a file to a specified (and smaller) number of bytes. */
parse arg siz FID /*obtain required arguments from the CL*/
parse arg siz FID /*obtain required arguments from the CL*/
FID=strip(FID) /*elide FID leading/trailing blanks. */
FID=strip(FID) /*elide FID leading/trailing blanks. */
Line 1,255: Line 1,255:
exit /*stick a fork in it, we're all done. */
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
ser: say '***error***' arg(1); exit 13 /*display an error message and exit. */</lang>
ser: say '***error***' arg(1); exit 13 /*display an error message and exit. */</syntaxhighlight>
For this example, Windows/XP and Windows 7 operating systems were used, the program was tested with:
For this example, Windows/XP and Windows 7 operating systems were used, the program was tested with:
:::* &nbsp; Personal REXX
:::* &nbsp; Personal REXX
Line 1,269: Line 1,269:


===with memory constraints===
===with memory constraints===
<lang rexx>/*REXX program truncates a file to a specified (and smaller) number of bytes. */
<syntaxhighlight lang="rexx">/*REXX program truncates a file to a specified (and smaller) number of bytes. */
parse arg siz FID /*obtain required arguments from the CL*/
parse arg siz FID /*obtain required arguments from the CL*/
FID=strip(FID) /*elide FID leading/trailing blanks. */
FID=strip(FID) /*elide FID leading/trailing blanks. */
Line 1,295: Line 1,295:
exit /*stick a fork in it, we're all done. */
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
ser: say '***error***' arg(1); exit 13 /*display an error message and exit. */</lang>
ser: say '***error***' arg(1); exit 13 /*display an error message and exit. */</syntaxhighlight>
'''output''' &nbsp; is identical to the 1<sup>st</sup> REXX version. <br><br>
'''output''' &nbsp; is identical to the 1<sup>st</sup> REXX version. <br><br>


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
file = "C:\Ring\ReadMe.txt"
file = "C:\Ring\ReadMe.txt"
fp = read(file)
fp = read(file)
Line 1,305: Line 1,305:
see fpstr + nl
see fpstr + nl
write(file, fpstr)
write(file, fpstr)
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 1,317: Line 1,317:
This only works with some platforms. If truncation is not available, then Ruby raises NotImplementedError.
This only works with some platforms. If truncation is not available, then Ruby raises NotImplementedError.


<lang ruby># Open a file for writing, and truncate it to 1234 bytes.
<syntaxhighlight lang="ruby"># Open a file for writing, and truncate it to 1234 bytes.
File.open("file", "ab") do |f|
File.open("file", "ab") do |f|
f.truncate(1234)
f.truncate(1234)
Line 1,324: Line 1,324:


# Just truncate a file to 567 bytes.
# Just truncate a file to 567 bytes.
File.truncate("file", 567)</lang>
File.truncate("file", 567)</syntaxhighlight>


=={{header|Rust}}==
=={{header|Rust}}==
<lang rust>use std::path::Path;
<syntaxhighlight lang="rust">use std::path::Path;
use std::fs;
use std::fs;


Line 1,350: Line 1,350:
/// Likely due to having read but not write permissions
/// Likely due to having read but not write permissions
UnableToWrite,
UnableToWrite,
}</lang>
}</syntaxhighlight>


=={{header|Scala}}==
=={{header|Scala}}==
{{libheader|Scala}}<lang Scala>import java.io.FileOutputStream
{{libheader|Scala}}<syntaxhighlight lang="scala">import java.io.FileOutputStream


object TruncFile extends App {
object TruncFile extends App {
Line 1,362: Line 1,362:
outChan.truncate(newSize)
outChan.truncate(newSize)
}
}
}</lang>
}</syntaxhighlight>


=={{header|Sidef}}==
=={{header|Sidef}}==
<lang ruby>func truncate(filename, len) {
<syntaxhighlight lang="ruby">func truncate(filename, len) {
var file = File(filename);
var file = File(filename);
len > file.size ->
len > file.size ->
Line 1,373: Line 1,373:


# truncate "file.ext" to 1234 bytes
# truncate "file.ext" to 1234 bytes
truncate("file.ext", 1234);</lang>
truncate("file.ext", 1234);</syntaxhighlight>


=={{header|Standard ML}}==
=={{header|Standard ML}}==
{{works with|Unix}}
{{works with|Unix}}
This function behaves similarly to the ''truncate'' tool from the [[GNU]] coreutils: If the file does not exist yet, or the target length is larger than the current file size, the extended area appears zero-filled (usually resulting in a sparse file).
This function behaves similarly to the ''truncate'' tool from the [[GNU]] coreutils: If the file does not exist yet, or the target length is larger than the current file size, the extended area appears zero-filled (usually resulting in a sparse file).
<lang sml>local
<syntaxhighlight lang="sml">local
open Posix.FileSys
open Posix.FileSys
val perm = S.flags [S.irusr, S.iwusr, S.irgrp, S.iwgrp, S.iroth, S.iwoth]
val perm = S.flags [S.irusr, S.iwusr, S.irgrp, S.iwgrp, S.iroth, S.iwoth]
Line 1,388: Line 1,388:
ftruncate (fd, len); Posix.IO.close fd
ftruncate (fd, len); Posix.IO.close fd
end
end
end</lang>
end</syntaxhighlight>


=={{header|Tcl}}==
=={{header|Tcl}}==
<lang tcl>package require Tcl 8.5
<syntaxhighlight lang="tcl">package require Tcl 8.5


set f [open "file" r+]; # Truncation is done on channels
set f [open "file" r+]; # Truncation is done on channels
chan truncate $f 1234; # Truncate at a particular length (in bytes)
chan truncate $f 1234; # Truncate at a particular length (in bytes)
close $f</lang>
close $f</syntaxhighlight>


=={{header|UNIX Shell}}==
=={{header|UNIX Shell}}==
The dd(1) command can truncate a file. Because dd(1) would create the file, this example runs ls(1). If the file does not exist, then ls(1) prints an error. If the file exists, then dd(1) truncates the file or prints an error. Unix can extend a file, so there is no error if the length increases.
The dd(1) command can truncate a file. Because dd(1) would create the file, this example runs ls(1). If the file does not exist, then ls(1) prints an error. If the file exists, then dd(1) truncates the file or prints an error. Unix can extend a file, so there is no error if the length increases.


<lang bash># Truncate a file named "myfile" to 1440 kilobytes.
<syntaxhighlight lang="bash"># Truncate a file named "myfile" to 1440 kilobytes.
ls myfile >/dev/null &&
ls myfile >/dev/null &&
dd if=/dev/null of=myfile bs=1 seek=1440k</lang>
dd if=/dev/null of=myfile bs=1 seek=1440k</syntaxhighlight>


----
----
Some systems have a truncate(1) command ([http://www.freebsd.org/cgi/man.cgi?query=truncate&apropos=0&sektion=0&manpath=FreeBSD+8.2-RELEASE&format=html FreeBSD truncate(1)], [http://www.gnu.org/software/coreutils/manual/html_node/truncate-invocation.html#truncate-invocation GNU truncate(1)]).
Some systems have a truncate(1) command ([http://www.freebsd.org/cgi/man.cgi?query=truncate&apropos=0&sektion=0&manpath=FreeBSD+8.2-RELEASE&format=html FreeBSD truncate(1)], [http://www.gnu.org/software/coreutils/manual/html_node/truncate-invocation.html#truncate-invocation GNU truncate(1)]).


<lang bash># Truncate a file named "myfile" to 1440 kilobytes.
<syntaxhighlight lang="bash"># Truncate a file named "myfile" to 1440 kilobytes.
truncate -s 1440k myfile</lang>
truncate -s 1440k myfile</syntaxhighlight>


----
----
Pure bourne-shell approach (cross-OS, no truncate(1) binary required)
Pure bourne-shell approach (cross-OS, no truncate(1) binary required)
<lang bash>
<syntaxhighlight lang="bash">
# 1. simplest one-liner
# 1. simplest one-liner
-bash$ >file
-bash$ >file
Line 1,500: Line 1,500:
abc+ echo _EOF_
abc+ echo _EOF_
_EOF_
_EOF_
</syntaxhighlight>
</lang>


NOTE[4]: Designed for regular text files. Does not work when files contain: chars 0x00 and 0xFF as of bash 4.2 - these chars are treated differently in read -N. For this reason use of method#4 is not prefer over dd(1) or truncate(1) when using binary files, or large files. [4b] http://unix.stackexchange.com/questions/8618/script-that-keep-reading-a-stream,[4a] https://groups.google.com/forum/#!topic/gnu.bash.bug/a2rjQHpQYSU
NOTE[4]: Designed for regular text files. Does not work when files contain: chars 0x00 and 0xFF as of bash 4.2 - these chars are treated differently in read -N. For this reason use of method#4 is not prefer over dd(1) or truncate(1) when using binary files, or large files. [4b] http://unix.stackexchange.com/questions/8618/script-that-keep-reading-a-stream,[4a] https://groups.google.com/forum/#!topic/gnu.bash.bug/a2rjQHpQYSU


=={{header|VBScript}}==
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
<lang vb>
Sub truncate(fpath,n)
Sub truncate(fpath,n)
'Check if file exist
'Check if file exist
Line 1,545: Line 1,545:
'testing
'testing
Call truncate("C:\temp\test.txt",30)
Call truncate("C:\temp\test.txt",30)
</syntaxhighlight>
</lang>


=={{header|Wren}}==
=={{header|Wren}}==
{{libheader|Wren-ioutil}}
{{libheader|Wren-ioutil}}
<lang ecmascript>import "/ioutil" for FileUtil
<syntaxhighlight lang="ecmascript">import "/ioutil" for FileUtil


var fileName = "temp.txt"
var fileName = "temp.txt"
Line 1,563: Line 1,563:
// attempt to truncate file to 20 bytes
// attempt to truncate file to 20 bytes
FileUtil.truncate(fileName, 20)
FileUtil.truncate(fileName, 20)
System.print("Contents are still : %(FileUtil.read(fileName))")</lang>
System.print("Contents are still : %(FileUtil.read(fileName))")</syntaxhighlight>


{{out}}
{{out}}
Line 1,574: Line 1,574:
=={{header|XPL0}}==
=={{header|XPL0}}==
Works for binary files.
Works for binary files.
<lang XPL0>int I, Size, FD;
<syntaxhighlight lang="xpl0">int I, Size, FD;
char C, FN(80), Array;
char C, FN(80), Array;
[I:= 0; \get file name from command line
[I:= 0; \get file name from command line
Line 1,605: Line 1,605:
for I:= 0 to Size-1 do ChOut(3, Array(I));
for I:= 0 to Size-1 do ChOut(3, Array(I));
Close(3);
Close(3);
]</lang>
]</syntaxhighlight>


=={{header|ZX Spectrum Basic}}==
=={{header|ZX Spectrum Basic}}==
Line 1,611: Line 1,611:
We can truncate files that were saved as binary. We don't know the length of the original file, so if the provided length is longer, then the file will be extended.
We can truncate files that were saved as binary. We don't know the length of the original file, so if the provided length is longer, then the file will be extended.


<lang zxbasic>10 CLEAR 29999
<syntaxhighlight lang="zxbasic">10 CLEAR 29999
20 INPUT "Which file do you want to truncate?";f$
20 INPUT "Which file do you want to truncate?";f$
30 PRINT "Start tape to load file to truncate."
30 PRINT "Start tape to load file to truncate."
Line 1,618: Line 1,618:
60 PRINT "Please rewind the tape and press record."
60 PRINT "Please rewind the tape and press record."
70 SAVE f$ CODE 30000,n
70 SAVE f$ CODE 30000,n
80 STOP</lang>
80 STOP</syntaxhighlight>


{{omit from|GUISS}}
{{omit from|GUISS}}