Skip to Main Content
Ruby. Receptury
book

Ruby. Receptury

by Lucas Carlson, Leonard Richardson
November 2012
Intermediate to advanced content levelIntermediate to advanced
888 pages
54h 46m
Polish
Helion
Content preview from Ruby. Receptury

6.19. Obcinanie pliku

Problem

Chcemy obciąć plik do zadanej długości, być może zerowej.

Rozwiązanie

Otwarcie pliku w trybie do zapisu powoduje obcięcie go do zerowej długości, po czym można wpisywać do niego nową zawartość:

filename = 'truncate.txt'
open(filename, 'w') { |f| f << "To wszystko zostanie obcięte." }
File.size(filename)                        # => 30

f = open(filename, 'w') {}
File.size(filename)                        # => 0

Obcięcia pliku do zerowej długości można także dokonać, podając jako tryb otwarcia File:TRUNC:

open(filename, 'w') { |f| f << "To jest nowa zawartość." }

File.size(filename)                       # => 27

f = open(filename, File::TRUNC) {}
File.size(filename)                       # => 0

Na pliku otwartym w trybie File::TRUNC nie da się wykonać żadnej operacji:

open(filename, File::TRUNC) ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

ReasonML Quick Start Guide

ReasonML Quick Start Guide

Raphael Rafatpanah, Bruno Joseph D'mello
Microsoft Excel: Formeln & Funktionen - Das Maxibuch, 3., aktualisierte und erweiterte Auflage

Microsoft Excel: Formeln & Funktionen - Das Maxibuch, 3., aktualisierte und erweiterte Auflage

Egbert Jeschke, Eckehard Pfeifer, Helmut Reinke, Sara Unverhau, Bodo Fienitz
Mastering Ruby Closures

Mastering Ruby Closures

Benjamin Tan Wei Hao

Publisher Resources

ISBN: 9781457177453Errata Page