E / S de Archivo en Todos los Lenguajes de Programación [cerrado]


Esta tiene que ser una pregunta común que todos los programadores tienen de vez en cuando. ¿Cómo leo una línea de un archivo de texto? Entonces la siguiente pregunta es siempre cómo lo escribo de nuevo.

Por supuesto, la mayoría de ustedes usan un marco de alto nivel en la programación del día a día (que está bien usar en las respuestas), pero a veces es bueno saber cómo hacerlo a un nivel bajo también.

Yo sé cómo hacerlo en C, C++ y Objective-C, pero seguro que sería útil para ver cómo se hace en todos los idiomas populares, aunque solo sea para ayudarnos a tomar una mejor decisión sobre en qué idioma hacer nuestro archivo io. En particular, creo que sería interesante ver cómo se hace en los lenguajes de manipulación de cadenas, como: python, ruby y por supuesto perl.

Así que me imagino que aquí podemos crear un recursos de la comunidad que todos podemos estrella a nuestros perfiles y consulte cuando necesitamos hacer archivo E/S en algún idioma nuevo. Por no hablar de la exposición todos llegaremos a idiomas con los que no tratamos en el día a día.

Así es como debes responder:

  1. Crea un nuevo archivo de texto llamado " fileio.txt "
  2. Escriba la primera línea "hola" en el archivo de texto.
  3. Añada la segunda línea "world" al archivo de texto.
  4. Lee la segunda línea "world" en una cadena de entrada.
  5. Imprimir la cadena de entrada a la consola.

Aclaración:

  • Debe mostrar cómo hacer esto en un solo lenguaje de programación por respuesta.
  • Supongamos que el archivo de texto no existe de antemano
  • No es necesario volver a abrir el archivo de texto después de escribir la primera línea

No hay límite particular en el idioma. C, C++, C#, Java, Objective-C son todos grandes.

Si usted sabe cómo hacerlo en Prolog, Haskell, Fortran, Lisp, o Basic entonces, por favor vaya adelante.

Author: Brock Woolf, 2010-08-21

30 answers

Python 3

with open('fileio.txt', 'w') as f:
   f.write('hello')
with open('fileio.txt', 'a') as f:
   f.write('\nworld')
with open('fileio.txt') as f:
   s = f.readlines()[1]
print(s)

Aclaraciones

  • Readlines () devuelve una lista de todas las líneas del archivo. Por lo tanto, la invocación de readlines() resulta en la lectura de todas y cada una de las líneas del archivo. En ese caso en particular, está bien usar readlines () porque tenemos que leer todo el archivo de todos modos (queremos su última línea). Pero si nuestro archivo contiene muchas líneas y solo queremos imprimir su enésima línea, no es necesario leer todo file. Aquí hay algunas formas mejores de obtener la enésima línea de un archivo en Python: ¿Qué sustituye a xreadlines() en Python 3?.

  • ¿Qué es esto con la declaración? La instrucción with inicia un bloque de código donde puede usar la variable f como un objeto de flujo devuelto desde la llamada a open(). Cuando el bloque with termina, python llama a f. close () automáticamente. Esto garantiza que el archivo se cerrará cuando salga del bloque with sin importar cómo o cuándo salga del bloque (incluso si sale a través de una excepción no controlada). Podrías llamar a f.close() explícitamente, pero ¿qué pasa si tu código genera una excepción y no llegas a la llamada a f. close ()? Es por eso que la declaración with es útil.

  • No es necesario volver a abrir el archivo antes de cada operación. Puedes escribir todo el código dentro de uno con block.

    with open('fileio.txt', 'w+') as f:
        f.write('hello')
        f.write('\nworld')
        s = f.readlines()[1]
    print(s)
    

    Usé tres con bloques para enfatizar la diferencia entre las tres operaciones: escribir (modo' w'), anexar (modo 'a'), leer (modo 'r', el predeterminado).

 48
Author: snakile,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:26:33

LOLCODE

Las especificaciones son incompletas por decir lo menos, pero hice lo mejor que pude. ¡Que comience la votación negativa! :) Todavía lo encuentro un ejercicio divertido.

HAI
CAN HAS STDIO?
PLZ OPEN FILE "FILEIO.TXT" ITZ "TehFilez"?
    AWSUM THX
        BTW #There is no standard way to output to files yet...
        VISIBLE "Hello" ON TehFilez
        BTW #There isn't a standard way to append to files either...
        MOAR VISIBLE "World" ON TehFilez
        GIMMEH LINES TehLinez OUTTA TehFilez
        I HAS A SecondLine ITZ 1 IN MAH TehLinez
        VISIBLE SecondLine
    O NOES
        VISIBLE "OH NOES!!!"
KTHXBYE
 242
Author: Danita,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-08-21 22:20:07

Cerebro * * * k

,------------------------------------------------>,------------------------------------------------>,------------------------------------------------>[-]+++++++++>[-]+++++++++>[-]+++++++++<<<<<[>>>>>>+>>>+<<<<<<<<<-]>>>>>>>>>[<<<<<<<<<+>>>>>>>>>-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<<<[>>>>>>+>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]>>[-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<[>>>>+>+<<<<<-]>>>>>[<<<<<+>>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<<<->>>->>>>>[-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<[>>>>+>+<<<<<-]>>>>>[<<<<<+>>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>][-]<<<<<<<[>>>>>+>>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]<<<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<<->>>->>>>[-]<<<<<<<[>>>>>+>>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]<<<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>][-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<->>>->>>[-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>]<[-]+<[-]+<<<<<<[>>>>>>[-]<<<<<<[-]]>>>>>>[[-]+<<<<<[>>>>>[-]<<<<<[-]]>>>>>[[-]+<<<<[>>>>[-]<<<<[-]]>>>>[[-]+<<<[>>>[-]<<<[-]]>>>[[-]+<<[>>[-]<<[-]]>>[[-]+<[>[-]<[-]]>[[-]+++++++++++++++++++++++++++++++++++++++++++++++++.-...>[-]<[-]]<>[-]]<<>>[-]]<<<>>>[-]]<<<<>>>>[-],------------------------------------------------>,------------------------------------------------>,------------------------------------------------>[-]+++++++++>[-]+++++++++>[-]+++++++++<<<<<[>>>>>>+>>>+<<<<<<<<<-]>>>>>>>>>[<<<<<<<<<+>>>>>>>>>-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<<<[>>>>>>+>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]>>[-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<[>>>>+>+<<<<<-]>>>>>[<<<<<+>>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<<<->>>->>>>>[-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<[>>>>+>+<<<<<-]>>>>>[<<<<<+>>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>][-]<<<<<<<[>>>>>+>>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]<<<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<<->>>->>>>[-]<<<<<<<[>>>>>+>>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]<<<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>][-]<<<<<<[>>>>+>>+<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<<<[-]<+>>>>>>>>>[-]]><[-]]<<<<<<<<<++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++.>>>>>>>>[-]]
 43
Author: Svisstack,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-08-24 15:36:12

COBOL

Ya que nadie más lo hizo......

IDENTIFICATION DIVISION.
PROGRAM-ID.  WriteDemo.
AUTHOR.  Mark Mullin.
* Hey, I don't even have a cobol compiler

ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
    SELECT StudentFile ASSIGN TO "STUDENTS.DAT"
        ORGANIZATION IS LINE SEQUENTIAL.

DATA DIVISION.
FILE SECTION.
FD TestFile.
01 TestData.
   02  LineNum        PIC X.
   02  LineText       PIC X(72).

PROCEDURE DIVISION.
Begin.
    OPEN OUTPUT TestFile
    DISPLAY "This language is still around."

    PERFORM GetFileDetails
    PERFORM UNTIL TestData = SPACES
       WRITE TestData 
       PERFORM GetStudentDetails
    END-PERFORM
    CLOSE TestFile
    STOP RUN.

GetFileDetails.
    DISPLAY "Enter - Line number, some text"
    DISPLAY "NXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
    ACCEPT  TestData.
 42
Author: Mark Mullin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-08-22 15:25:14

Haskell

main :: IO ()
main = let filePath = "fileio.txt" in
       do writeFile filePath "hello"
          appendFile filePath "\nworld"
          fileLines <- readFile filePath
          let secondLine = (lines fileLines) !! 1
          putStrLn secondLine

Si solo desea leer/escribir un archivo:

main :: IO ()
main = readFile "somefile.txt" >>= writeFile "someotherfile.txt" 
 39
Author: Ionuț G. Stan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-08-22 04:23:44

D

module d_io;

import std.stdio;


void main()
{
    auto f = File("fileio.txt", "w");
    f.writeln("hello");
    f.writeln("world");

    f.open("fileio.txt", "r");
    f.readln;
    auto s = f.readln;
    writeln(s);
}
 35
Author: Bernard,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-08-21 23:50:00

Ruby

PATH = 'fileio.txt'
File.open(PATH, 'w') { |file| file.puts "hello" }
File.open(PATH, 'a') { |file| file.puts "world" }
puts line = File.readlines(PATH).last
 34
Author: Wayne Conrad,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-08-21 19:55:23

C #

string path = "fileio.txt";
File.WriteAllLines(path, new[] { "hello"}); //Will end it with Environment.NewLine
File.AppendAllText(path, "world");

string secondLine = File.ReadLines(path).ElementAt(1);
Console.WriteLine(secondLine);

File.ReadLines(path).ElementAt(1) es. Net 4.0 solamente, la alternativa es File.ReadAllLines(path)[1] que analiza todo el archivo en una matriz.

 33
Author: Lasse Espeholt,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-08-22 15:07:09

ANSI C

#include <stdio.h>
#include <stdlib.h>

int /*ARGSUSED*/
main(char *argv[0], int argc) {
   FILE *file;
   char buf[128];

   if (!(file = fopen("fileio.txt", "w")) {
      perror("couldn't open for writing fileio.txt");
      exit(1);
   }

   fprintf(file, "hello");
   fclose(file);

   if (!(file = fopen("fileio.txt", "a")) {
      perror("couldn't opened for appening fileio.txt");
      exit(1);
   }

   fprintf(file, "\nworld");
   fclose(file);

   if (!(file = fopen("fileio.txt", "r")) {
      perror("couldn't open for reading fileio.txt");
      exit(1);
   }

   fgets(buf, sizeof(buf), file);
   fgets(buf, sizeof(buf), file);

   fclose(file);

   puts(buf);

   return 0;
}
 29
Author: Maister,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-11-18 19:00:22

Shell Script (UNIX)

#!/bin/sh
echo "hello" > fileio.txt
echo "world" >> fileio.txt
LINE=`sed -ne2p fileio.txt`
echo $LINE

En realidad la parte sed -n "2p" imprime la segunda línea, pero la pregunta pide que la segunda línea se almacene en una variable y luego se imprima, así... :)

 29
Author: robertbasic,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-11-18 19:03:02

Ensamblador X86 (NASM) en Linux

No he tocado asm en 7 años, así que tuve que usar Google un poco para hackear esto juntos, pero aún así, funciona;) Sé que no es 100% correcto, pero hey: D

OK, no funciona. perdón por esto. si bien imprime world al final, no lo imprime desde el archivo, sino desde el ecx que se establece en la línea 27.

section .data
hello db 'hello',10
helloLen equ $-hello
world db 'world',10
worldLen equ $-world
helloFile db 'hello.txt'

section .text
global _start

_start:
mov eax,8
mov ebx,helloFile
mov ecx,00644Q
int 80h

mov ebx,eax

mov eax,4
mov ecx, hello
mov edx, helloLen
int 80h

mov eax,4
mov ecx, world
mov edx, worldLen
int 80h

mov eax,6
int 80h

mov eax,5
mov ebx,helloFile
int 80h

mov eax,3
int 80h

mov eax,4
mov ebx,1
int 80h

xor ebx,ebx
mov eax,1
int 80h

Referencias utilizar: http://www.cin.ufpe.br / ~if817/arquivos/asmtut/quickstart.html

Http://bluemaster.iu.hio.no/edu/dark/lin-asm/syscalls.html

Http://www.digilife.be/quickreferences/QRC/LINUX%20System%20Call%20Quick%20Reference.pdf

 27
Author: robertbasic,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-10-05 05:59:16

JavaScript - nodo.js

Primero, muchas devoluciones de llamada anidadas.

var fs   = require("fs");
var sys  = require("sys");
var path = "fileio.txt";

fs.writeFile(path, "hello", function (error) {
    fs.open(path, "a", 0666, function (error, file) {
        fs.write(file, "\nworld", null, "utf-8", function () {
            fs.close(file, function (error) {
                fs.readFile(path, "utf-8", function (error, data) {
                    var lines = data.split("\n");
                    sys.puts(lines[1]);
                });
            });
        });
    });
});

Un poco más limpio:

var writeString = function (string, nextAction) {
    fs.writeFile(path, string, nextAction);
};

var appendString = function (string, nextAction) {
    return function (error, file) {
        fs.open(path, "a", 0666, function (error, file) {
            fs.write(file, string, null, "utf-8", function () {
                fs.close(file, nextAction);
            });
        });
    };
};

var readLine = function (index, nextAction) {
    return function (error) {
        fs.readFile(path, "utf-8", function (error, data) {
            var lines = data.split("\n");
            nextAction(lines[index]);
        });
    };
};

var writeToConsole = function (line) {
    sys.puts(line);
};

writeString("hello", appendString("\nworld", readLine(1, writeToConsole)));
 21
Author: Ionuț G. Stan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-08-21 17:52:28

Lisp común

(defun main ()
  (with-open-file (s "fileio.txt" :direction :output :if-exists :supersede)
    (format s "hello"))
  (with-open-file (s "fileio.txt" :direction :io :if-exists :append)
    (format s "~%world")
    (file-position s 0)
    (loop repeat 2 for line = (read-line s nil nil) finally (print line))))
 21
Author: twopoint718,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-08-24 06:37:59

PowerShell

sc fileio.txt 'hello'
ac fileio.txt 'world'
$line = (gc fileio.txt)[1]
$line
 18
Author: Lasse Espeholt,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-08-21 22:00:56

Shell Script

Aquí hay un script de shell usando solo comandos incorporados, en lugar de invocar comandos externos como sed o tail como lo han hecho las respuestas anteriores.

#!/bin/sh

echo hello > fileio.txt             # Print "hello" to fileio.txt
echo world >> fileio.txt            # Print "world" to fileio.txt, appending
                                    # to what is already there
{ read input; read input; } < fileio.txt  
                                    # Read the first two lines of fileio.txt,
                                    # storing the second in $input
echo $input                         # Print the contents of $input

Al escribir scripts de shell significativos, es aconsejable usar builtins tanto como sea posible, ya que generar un proceso separado puede ser lento; a partir de una prueba rápida en mi máquina, la solución sed es aproximadamente 20 veces más lenta que usar read. Si vas a llamar sed una vez, como en este caso, no realmente importa mucho, ya que se ejecutará más rápido de lo que puedes notar, pero si vas a ejecutarlo cientos o miles de veces, puede sumar.

Para aquellos que no están familiarizados con la sintaxis, { y } ejecute una lista de comandos en el entorno actual del shell (a diferencia de ( y ) que crean un subshell; necesitamos estar operando en el entorno actual del shell, para que podamos usar el valor de la variable más adelante). Tenemos que agrupar los comandos juntos en para que ambos operen en el mismo flujo de entrada, creado redireccionando desde fileio.txt; si simplemente ejecutamos read < fileio.txt; read input < fileio.txt, solo obtendríamos la primera línea, ya que el archivo se cerraría y reabriría entre los dos comandos. Debido a una idiosincrasia de la sintaxis del shell ({ y } son palabras reservadas, a diferencia de los metacaracteres), necesitamos separar el { y } del resto de los comandos con espacios, y terminar la lista de comandos con un ;.

El read builtin toma como argumento los nombres de las variables a leer. Consume una línea de entrada, rompe la entrada por espacios en blanco (técnicamente, la rompe de acuerdo con el contenido de $IFS, que por defecto es un carácter de espacio, donde un carácter de espacio significa dividirlo en cualquier espacio, tabulación o nueva línea), asigna cada palabra a los nombres de variables dados en orden, y asigna el resto de la línea a la última variable. Ya que solo estamos suministrando una variable, solo pone toda la línea en esa variable. Reutilizamos la variable $input, ya que no nos importa lo que hay en la primera línea (si estamos usando Bash simplemente no podríamos proporcionar un nombre de variable, pero para ser portátil, siempre debe proporcionar al menos un nombre).

Tenga en cuenta que si bien puede leer líneas una a la vez, como lo hago aquí, un patrón mucho más común sería envolverlo en un bucle while:

while read foo bar baz
do
  process $foo $bar $baz
done < input.txt
 18
Author: Brian Campbell,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-08-23 16:55:42

Clojure

(use '[clojure.java.io :only (reader)])

(let [file-name "fileio.txt"]
  (spit file-name "hello")
  (spit file-name "\nworld" :append true)
  (println (second (line-seq (reader file-name)))))

O de forma equivalente, usando la macro de roscado -> (también conocida como el removedor de paren):

(use '[clojure.java.io :only (reader)])

(let [file-name "fileio.txt"] 
  (spit file-name "hello") 
  (spit file-name "\nworld" :append true) 
  (-> file-name reader line-seq second println))
 18
Author: Abhinav Sarkar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-09-09 16:13:25

F #

let path = "fileio.txt"
File.WriteAllText(path, "hello")
File.AppendAllText(path, "\nworld")

let secondLine = File.ReadLines path |> Seq.nth 1
printfn "%s" secondLine
 17
Author: Lasse Espeholt,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-08-21 17:14:23

BÁSICO

No he usado BASIC en casi 10 años, pero esta pregunta me dio una razón para repasar rápidamente mis conocimientos. :)

OPEN "fileio.txt" FOR OUTPUT AS 1
PRINT #1, "hello"
PRINT #1, "world"
CLOSE 1

OPEN "fileio.txt" FOR INPUT AS 1
LINE INPUT #1, A$
LINE INPUT #1, A$
CLOSE 1

PRINT A$
 16
Author: casablanca,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-08-21 16:53:37

Objective-C

NSFileHandle *fh = [NSFileHandle fileHandleForUpdatingAtPath:@"fileio.txt"];

[[NSFileManager defaultManager] createFileAtPath:@"fileio.txt" contents:nil attributes:nil];

[fh writeData:[@"hello" dataUsingEncoding:NSUTF8StringEncoding]];
[fh writeData:[@"\nworld" dataUsingEncoding:NSUTF8StringEncoding]];

NSArray *linesInFile = [[[NSString stringWithContentsOfFile:@"fileio.txt" 
                                             encoding:NSUTF8StringEncoding 
                                                error:nil] stringByStandardizingPath] 
                          componentsSeparatedByString:@"\n"];

NSLog(@"%@", [linesInFile objectAtIndex:1]);
 16
Author: Brock Woolf,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-08-24 10:31:04

Perl

#!/usr/bin/env perl

use 5.10.0;
use utf8;
use strict;
use autodie;
use warnings qw<  FATAL all     >;
use open     qw< :std  :utf8    >;

use English  qw< -no_match_vars >;

# and the last shall be first
END { close(STDOUT) }

my $filename = "fileio.txt";
my($handle, @lines);

$INPUT_RECORD_SEPARATOR = $OUTPUT_RECORD_SEPARATOR = "\n";

open($handle, ">",  $filename);
print $handle "hello";
close($handle);

open($handle, ">>", $filename);
print $handle "world";
close($handle);

open($handle, "<",  $filename);
chomp(@lines = <$handle>);
close($handle);

print STDOUT $lines[1];
 16
Author: Vivin Paliath,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-11-18 19:30:27

R:

cat("hello\n", file="fileio.txt")
cat("world\n", file="fileio.txt", append=TRUE)
line2 = readLines("fileio.txt", n=2)[2]
cat(line2)
 15
Author: David F,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-08-22 08:46:09

PHP

<?php

$filePath = "fileio.txt";

file_put_contents($filePath, "hello");
file_put_contents($filePath, "\nworld", FILE_APPEND);

$lines = file($filePath);

echo $lines[1];

// closing PHP tags are bad practice in PHP-only files, don't use them
 15
Author: Ionuț G. Stan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-08-22 13:39:53

Java

import java.io.*;
import java.util.*;

class Test {
  public static void  main(String[] args) throws IOException {
    String path = "fileio.txt";
    File file = new File(path);

    //Creates New File...
    try (FileOutputStream fout = new FileOutputStream(file)) {
      fout.write("hello\n".getBytes());
    }

    //Appends To New File...
    try (FileOutputStream fout2 = new FileOutputStream(file,true)) {
      fout2.write("world\n".getBytes());
    }

    //Reading the File...
    try (BufferedReader fin = new BufferedReader(new FileReader(file))) {
      fin.readLine();
      System.out.println(fin.readLine());
    }       
  }
}
 15
Author: st0le,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-10-05 06:25:44

C++

#include <limits>
#include <string>
#include <fstream>
#include <iostream>

int main() {
    std::fstream file( "fileio.txt",
        std::ios::in | std::ios::out | std::ios::trunc  );
    file.exceptions( std::ios::failbit );   

    file << "hello\n" // << std::endl, not \n, if writing includes flushing
         << "world\n";

    file.seekg( 0 )
        .ignore( std::numeric_limits< std::streamsize >::max(), '\n' );
    std::string input_string;
    std::getline( file, input_string );

    std::cout << input_string << '\n';
}

O algo menos pedánticamente,

#include <string>
#include <fstream>
#include <iostream>
using namespace std;

int main() {
    fstream file( "fileio.txt", ios::in | ios::out | ios::trunc  );
    file.exceptions( ios::failbit );   

    file << "hello" << endl
         << "world" << endl;

    file.seekg( 0 ).ignore( 10000, '\n' );
    string input_string;
    getline( file, input_string );

    cout << input_string << endl;
}
 14
Author: Potatoswatter,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-08-22 01:39:22

Go

package main

import (
  "os"
  "bufio"
  "log"
)

func main() {
  file, err := os.Open("fileio.txt", os.O_RDWR | os.O_CREATE, 0666)
  if err != nil {
    log.Exit(err)
  }
  defer file.Close()

  _, err = file.Write([]byte("hello\n"))
  if err != nil {
    log.Exit(err)
  }

  _, err = file.Write([]byte("world\n"))
  if err != nil {
    log.Exit(err)
  }

  // seek to the beginning 
  _, err = file.Seek(0,0)
  if err != nil {
    log.Exit(err)
  }

  bfile := bufio.NewReader(file)
  _, err = bfile.ReadBytes('\n')
  if err != nil {
    log.Exit(err)
  }

  line, err := bfile.ReadBytes('\n')
  if err != nil {
    log.Exit(err)
  }

  os.Stdout.Write(line)
}
 13
Author: eclark,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-08-21 22:46:36

Erlang

Probablemente no sea el Erlang más idiomático, pero:

#!/usr/bin/env escript

main(_Args) ->
  Filename = "fileio.txt",
  ok = file:write_file(Filename, "hello\n", [write]),
  ok = file:write_file(Filename, "world\n", [append]),
  {ok, File} = file:open(Filename, [read]),
  {ok, _FirstLine} = file:read_line(File),
  {ok, SecondLine} = file:read_line(File),
  ok = file:close(File),
  io:format(SecondLine).
 12
Author: clofresh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-08-21 19:05:37

Emacs Lisp

A pesar de lo que algunos dicen que Emacs es principalmente un editor de texto [1]. Así, aunque Emacs Lisp puede ser utilizado para resolver todo tipo de problemas, está optimizado para las necesidades de un editor de texto. Dado que los editores de texto (obviamente) tienen necesidades bastante específicas cuando se trata de cómo se manejan los archivos, esto afecta a la funcionalidad relacionada con los archivos que ofrece Emacs Lisp.

Básicamente esto significa que Emacs Lisp no ofrece funciones para abrir un archivo como una secuencia, y leerlo parte por parte. Del mismo modo, no se puede añadir a un archivo sin cargar el archivo completo primero. En su lugar, el archivo se lee completamente [2] en un búfer [3], se edita y luego se guarda en un archivo de nuevo.

Para las tareas must usarías Emacs Lisp para esto es adecuado y si quieres hacer algo que no implique editar se pueden usar las mismas funciones.

Si desea agregar a un archivo una y otra vez, esto viene con una sobrecarga enorme, pero es posible, como se demuestra aquí. En la práctica normalmente termina de hacer cambios en un búfer ya sea manual o programáticamente antes de escribir en un archivo (solo combina las dos primeras expresiones s en el ejemplo a continuación).

(with-temp-file "file"
  (insert "hello\n"))

(with-temp-file "file"
  (insert-file-contents "file")
  (goto-char (point-max))
  (insert "world\n"))

(with-temp-buffer
  (insert-file-contents "file")
  (next-line)
  (message "%s" (buffer-substring (point) (line-end-position))))

[1] Al menos no iría tan lejos como llamarlo un sistema operativo; una interfaz de usuario alternativa sí, un sistema operativo no.

[2] Solo puede cargar partes de un archivo, pero esto solo se puede especificar en bytes.

[3] Un búfer es tanto un tipo de datos en algunos aspectos similar a una cadena, así como la "cosa que se ve mientras se edita un archivo". Mientras se edita un búfer se muestra en una ventana, pero los búferes no necesariamente tienen que ser visibles para el usuario.

Editar: Si desea ver el texto insertado en el búfer, obviamente debe hacerlo visible y dormir entre acciones. Debido a que Emacs normalmente solo vuelve a mostrar la pantalla cuando espera la entrada del usuario (y dormir no es lo mismo que esperar la entrada), también tiene que forzar la redisplay. Esto es necesario en este ejemplo( úselo en lugar del segundo sexp); en práctica Nunca tuve que usar 'redisplay' ni una sola vez, así que sí, esto es feo, pero ...

(with-current-buffer (generate-new-buffer "*demo*")
  (pop-to-buffer (current-buffer))
  (redisplay)
  (sleep-for 1)
  (insert-file-contents "file")
  (redisplay)
  (sleep-for 1)
  (goto-char (point-max))
  (redisplay)
  (sleep-for 1)
  (insert "world\n")
  (redisplay)
  (sleep-for 1)
  (write-file "file"))
 12
Author: tarsius,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-09-10 18:27:46

Archivos por lotes de Windows-Versión #2

@echo off
echo hello > fileio.txt
echo world  >> fileio.txt
set /P answer=Insert: 
echo %answer%  >> fileio.txt
for /f "skip=1 tokens=*" %%A in (fileio.txt) do echo %%A

Para explicar ese último bucle horrible, asume que solo hay hello (nueva línea) world en el archivo. Por lo que sólo se salta la primera línea y ecos sólo la segunda.

Lista de cambios

  • 2 - Opps, debe haber malinterpretado los requisitos o me han cambiado. Ahora lee la última línea del archivo

 11
Author: TheLQ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-08-21 19:37:17

Scala:

Usando la biblioteca estándar:

val path = "fileio.txt"
val fout = new FileWriter(path)
fout write "hello\n"
fout.close()
val fout0 = new FileWriter(path, true)
fout0 write "world\n"
fout0.close() 
val str = Source.fromFile(path).getLines.toSeq(1)
println(str)

Usando la Biblioteca Scala-ARM de Josh Suereth :

val path = "fileio.txt"
for(fout <- managed(new FileWriter(path))) 
  fout write "hello\n"
for(fout <- managed(new FileWriter(path, true))) 
  fout write "world\n"
val str = Source.fromFile(path).getLines.toSeq(1)
println(str)      


Dado que muchas personas han utilizado el mismo descriptor de archivo para escribir las dos cadenas, también estoy incluyendo esa manera en mi respuesta.

Usando la biblioteca estándar:

val path = "fileio.txt"
val fout = new FileWriter(path)
fout write "hello\n"
fout write "world\n"
fout.close()
val str = Source.fromFile(path).getLines.toSeq(1)
println(str)

Usando la Biblioteca Scala-ARM de Josh Suereth :

val path = "fileio.txt"
for(fout <- managed(new FileWriter(path))){
  fout write "hello\n"
  fout write "world\n"
}
val str = Source.fromFile(path).getLines.toSeq(1)
println(str)
 11
Author: missingfaktor,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-08-25 15:44:41

Groovy

new File("fileio.txt").with { 
    write  "hello\n"
    append "world\n"   
    println secondLine = readLines()[1]
}
 11
Author: Wayne Keenan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-12-05 23:08:03