web-dev-qa-db-fra.com

Fichier I / O dans chaque langage de programmation

Cela doit être une question commune à tous les programmeurs de temps en temps. Comment lire une ligne d'un fichier texte? Ensuite, la prochaine question est toujours comment puis-je l'écrire à nouveau.

Bien sûr, la plupart d’entre vous utilisez un cadre de haut niveau dans la programmation quotidienne (ce qui est bien pour les réponses), mais il est parfois agréable de savoir comment le faire à un niveau bas aussi.

Je sais moi-même comment le faire dans C, C++ et Objective-C, mais il serait certainement utile de voir comment cela fonctionne dans toutes les langues populaires, ne serait-ce que pour nous aider à prendre une meilleure décision quant à la langue dans laquelle notre fichier doit être écrit. En particulier, je pense qu'il serait intéressant de voir comment cela se fait dans les langages de manipulation de chaînes, comme: python, Ruby et bien sûr Perl.

Je pense donc que nous pouvons créer une ressource de la communauté que nous pouvons tous star à nos profils et à faire référence lorsque nous devons faire fichier I/O dans une nouvelle langue. Sans parler de l'exposition que nous allons tous avoir à des langues avec lesquelles nous ne travaillons pas quotidiennement.

Voici comment vous devez répondre:

  1. Créez un nouveau fichier texte appelé "fileio.txt"
  2. Écrivez la première ligne "bonjour" dans le fichier texte.
  3. Ajoutez la deuxième ligne "world" au fichier texte.
  4. Lire la deuxième ligne "world" dans une chaîne d'entrée.
  5. Imprimez la chaîne d'entrée sur la console.

Clarification:

  • Vous devriez montrer comment faire cela dans un seul langage de programmation par réponse.
  • Supposons que le fichier texte n'existe pas auparavant
  • Vous n'avez pas besoin de rouvrir le fichier texte après avoir écrit la première ligne

Pas de limite particulière sur la langue. C, C++, C#, Java, Objective-C sont tous géniaux.

Si vous savez comment le faire dans Prolog, Haskell, Fortran, LISP ou Basic, veuillez continuer immédiatement.

127
Brock Woolf

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)

Clarifications

  • readlines () renvoie une liste de toutes les lignes du fichier. Par conséquent, l'invocation de readlines () entraîne la lecture de chaque ligne du fichier. Dans ce cas particulier, il est bon d’utiliser readlines () car nous devons quand même lire le fichier dans son intégralité (nous voulons sa dernière ligne). Mais si notre fichier contient plusieurs lignes et que nous souhaitons simplement imprimer sa nième ligne, il est inutile de lire le fichier en entier. Voici quelques meilleures façons d’obtenir la nième ligne d’un fichier en Python: Qu'est-ce qui substitue xreadlines () dans Python 3? .

  • Qu'est-ce que c'est avec la déclaration? L'instruction with commence un bloc de code dans lequel vous pouvez utiliser la variable f en tant que objet flux renvoyé par l'appel à open (). Lorsque le bloc with se termine, python appelle f.close () automatiquement. Cela garantit que le fichier sera fermé lorsque vous quitterez le bloc with, peu importe comment et quand vous le quitterez (même si vous le quittez. quittez-le via une exception non gérée). Vous pouvez appeler explicitement f.close (), mais que se passe-t-il si votre code lève une exception et que vous n'obtenez pas l'appel f.close ()? C'est pourquoi l'instruction with est utile.

  • Vous n'avez pas besoin de rouvrir le fichier avant chaque opération. Vous pouvez écrire tout le code dans un code avec bloc.

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

    J'en ai utilisé trois avec des blocs pour exprimer la différence entre les trois opérations: write (mode 'w'), append (mode 'a'), read (mode 'r', le mode par défaut).

48
snakile

LOLCODE

Les spécifications sont peu précis pour le moins, mais j'ai fait de mon mieux. Commençons par le vote négatif! :) Je trouve toujours que c'est un exercice amusant.

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
Danita

Cerveau *** k

,------------------------------------------------>,------------------------------------------------>,------------------------------------------------>[-]+++++++++>[-]+++++++++>[-]+++++++++<<<<<[>>>>>>+>>>+<<<<<<<<<-]>>>>>>>>>[<<<<<<<<<+>>>>>>>>>-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<<<[>>>>>>+>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]>>[-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<[>>>>+>+<<<<<-]>>>>>[<<<<<+>>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<<<->>>->>>>>[-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<[>>>>+>+<<<<<-]>>>>>[<<<<<+>>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>][-]<<<<<<<[>>>>>+>>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]<<<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<<->>>->>>>[-]<<<<<<<[>>>>>+>>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]<<<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>][-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<->>>->>>[-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>]<[-]+<[-]+<<<<<<[>>>>>>[-]<<<<<<[-]]>>>>>>[[-]+<<<<<[>>>>>[-]<<<<<[-]]>>>>>[[-]+<<<<[>>>>[-]<<<<[-]]>>>>[[-]+<<<[>>>[-]<<<[-]]>>>[[-]+<<[>>[-]<<[-]]>>[[-]+<[>[-]<[-]]>[[-]+++++++++++++++++++++++++++++++++++++++++++++++++.-...>[-]<[-]]<>[-]]<<>>[-]]<<<>>>[-]]<<<<>>>>[-],------------------------------------------------>,------------------------------------------------>,------------------------------------------------>[-]+++++++++>[-]+++++++++>[-]+++++++++<<<<<[>>>>>>+>>>+<<<<<<<<<-]>>>>>>>>>[<<<<<<<<<+>>>>>>>>>-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<<<[>>>>>>+>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]>>[-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<[>>>>+>+<<<<<-]>>>>>[<<<<<+>>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<<<->>>->>>>>[-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<[>>>>+>+<<<<<-]>>>>>[<<<<<+>>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>][-]<<<<<<<[>>>>>+>>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]<<<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<<->>>->>>>[-]<<<<<<<[>>>>>+>>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]<<<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>][-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<->>>->>>[-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>]<[-]+<[-]+<<<<<<[>>>>>>[-]<<<<<<[-]]>>>>>>[[-]+<<<<<[>>>>>[-]<<<<<[-]]>>>>>[[-]+<<<<[>>>>[-]<<<<[-]]>>>>[[-]+<<<[>>>[-]<<<[-]]>>>[[-]+<<[>>[-]<<[-]]>>[[-]+<[>[-]<[-]]>[[-]+++++++++++++++++++++++++++++++++++++++++++++++++.-...>[-]<[-]]<>[-]]<<>>[-]]<<<>>>[-]]<<<<>>>>[-]]<<<<<>>>>>[-]]<<<<<<>>>>>>>[<<<<<<<<[>>>>>>+>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]>[-]++++++++++<<+<<<<<<+>>>>>>>>>>>[-]<<<<<[>>>+>>+<<<<<-]>>>>>[<<<<<+>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<->>->>>[-]<<<<<[>>>+>>+<<<<<-]>>>>>[<<<<<+>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>]<<<<[-]+<[>[-]<[-]]>[[-]+>[<[-]>[-]]<[<<<<<<<[-]<+>>>>>>>>[-]]><[-]]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]>[-]++++++++++>>>[-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<->>>->>>[-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>]<<<<[-]+<<[>>[-]<<[-]]>>[[-]+>[<[-]>[-]]<[<<<<<<<<[-]<+>>>>>>>>>[-]]><[-]]<<<<<<<<<++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++.>>>>>>>>[-]]]<<<<<>>>>>[-]]<<<<<<>>>>>>>[<<<<<<<<[>>>>>>+>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]>[-]++++++++++<<+<<<<<<+>>>>>>>>>>>[-]<<<<<[>>>+>>+<<<<<-]>>>>>[<<<<<+>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<->>->>>[-]<<<<<[>>>+>>+<<<<<-]>>>>>[<<<<<+>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>]<<<<[-]+<[>[-]<[-]]>[[-]+>[<[-]>[-]]<[<<<<<<<[-]<+>>>>>>>>[-]]><[-]]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]>[-]++++++++++>>>[-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<->>>->>>[-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>]<<<<[-]+<<[>>[-]<<[-]]>>[[-]+>[<[-]>[-]]<[<<<<<<<<[-]<+>>>>>>>>>[-]]><[-]]<<<<<<<<<++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++.>>>>>>>>[-]]
43
Svisstack

COBOL

Puisque personne d'autre n'a fait ......

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
Mark Mullin

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 vous voulez juste lire/écrire un fichier:

main :: IO ()
main = readFile "somefile.txt" >>= writeFile "someotherfile.txt" 
39
Ionuț G. Stan

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
Bernard

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
Wayne Conrad

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) est uniquement .Net 4.0, l'alternative est File.ReadAllLines(path)[1] qui analyse l'ensemble du fichier dans un tableau.

33
Lasse Espeholt

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
Maister

Script shell (UNIX)

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

En fait, le sed -n "2p" partie imprime la deuxième ligne, mais la question demande à la deuxième ligne à être stockée dans une variable, puis imprimée, donc ... :)

29
robertbasic

assembleur x86 (NASM) sous Linux

Je ne l'ai pas touché depuis 7 ans, alors j'ai dû utiliser un peu Google pour bidouiller cela, mais ça marche quand même;) Je sais que ce n'est pas correct à 100%, mais bon: D

OK, ça ne marche pas. désolé pour ça. bien qu’il imprime finalement world, il ne l’imprimera pas à partir du fichier, mais à partir du ecx défini à la ligne 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

Références utilisées: 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
robertbasic

LISP commun

(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
Chris

JavaScript - node.js

Tout d'abord, beaucoup de rappels imbriqués.

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 peu plus propre:

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
Ionuț G. Stan

Script shell

Voici un script Shell utilisant uniquement des commandes intégrées, plutôt que d'appeler des commandes externes telles que sed ou tail comme les réponses précédentes.

#!/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

Lors de l'écriture de scripts Shell importants, il est conseillé d'utiliser autant que possible les commandes intégrées, car la création d'un processus distinct peut être lente; à l’aide d’un test rapide sur ma machine, la solution sed est environ 20 fois plus lente que l’utilisation de read. Si vous appelez sed une fois, comme dans ce cas, cela n'a pas beaucoup d'importance, car l'exécution sera plus rapide que vous ne le remarquerez, mais si vous l'exécutez par centaines, des milliers de fois, cela peut s'additionner.

Pour ceux qui ne connaissent pas la syntaxe, { et }exécute une liste de commandes dans l’environnement Shell actuel (par opposition à ( et ) qui crée un sous-shell; nous devons fonctionner dans l’environnement Shell actuel pour pouvoir utiliser la valeur de la variable ultérieurement). Nous devons regrouper les commandes afin qu'elles fonctionnent toutes les deux sur le même flux d'entrée, créé en redirigeant à partir de fileio.txt; si nous avons simplement couru read < fileio.txt; read input < fileio.txt, nous obtiendrions simplement la première ligne car le fichier serait fermé et rouvert entre les deux commandes. En raison d’une idiosyncrasie de la syntaxe Shell ({ et } sont des mots réservés, par opposition aux métacaractères), nous devons séparer les { et } du reste des commandes avec des espaces et termine la liste de commandes avec un ;.

Le read builtin prend en argument les noms des variables à lire. Il consomme une ligne d'entrée, interrompt l'entrée par des espaces (techniquement, il l'interrompt en fonction du contenu de $IFS, qui prend par défaut un caractère d'espacement, un espace signifie de le scinder en espaces, tabulations ou sauts de ligne), attribue à chaque mot les noms de variables donnés dans l'ordre, et attribue le reste de la ligne à la dernière variable . Comme nous ne fournissons qu'une seule variable, la ligne entière est simplement insérée dans cette variable. Nous réutilisons le $input variable, puisque nous ne nous soucions pas de ce qui se trouve sur la première ligne (si nous utilisons Bash, nous pourrions simplement ne pas fournir de nom de variable, mais pour être portables, vous devez toujours fournir au moins un nom).

Notez que bien que vous puissiez lire les lignes une par une, comme je le fais ici, un schéma beaucoup plus courant serait de l’envelopper dans une boucle while:

while read foo bar baz
do
  process $foo $bar $baz
done < input.txt
18
Brian Campbell

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)))))

Ou de manière équivalente, en utilisant la macro de threading -> (également connu sous le nom de dissolvant 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
Abhinav Sarkar

PowerShell

sc fileio.txt 'hello'
ac fileio.txt 'world'
$line = (gc fileio.txt)[1]
$line
18
Lasse Espeholt

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
Lasse Espeholt

DE BASE

Je n’ai pas utilisé BASIC depuis presque 10 ans, mais cette question m’a donné une raison de parfaire rapidement mes connaissances. :)

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
casablanca

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
Brock Woolf

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
Vivin Paliath

R:

 cat ("hello\n", fichier = "fileio.txt") 
 cat ("monde\n", fichier = "fileio.txt", append = TRUE) 
 line2 = readLines ("fileio.txt", n = 2) [2] 
 cat (line2) 
15
David F

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
Ionuț G. Stan

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
st0le

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';
}

ou un peu moins pédantiquement,

#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
Potatoswatter

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
eclark

Erlang

Probablement pas l’Erlang le plus idiomatique, mais:

#!/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
clofresh

LISP Emacs

Malgré ce que certaines personnes disent, Emacs est principalement un éditeur de texte [1]. Ainsi, bien qu'Emacs LISP puisse être utilisé pour résoudre toutes sortes de problèmes, il est optimisé pour répondre aux besoins d'un éditeur de texte. Étant donné que les éditeurs de texte (évidemment) ont des besoins spécifiques en ce qui concerne le traitement des fichiers, les fonctionnalités associées aux fichiers proposées par Emacs, LISP, sont affectées.

En gros, cela signifie qu'Emacs LISP n'offre pas de fonctions permettant d'ouvrir un fichier sous forme de flux et de le lire partie par partie. De même, vous ne pouvez pas ajouter à un fichier sans d'abord charger le fichier entier. Au lieu de cela, le fichier est complètement lu dans un tampon, édité puis sauvegardé dans un fichier.

Pour ce faire, vous devez utiliser Emacs LISP, car si vous souhaitez effectuer quelque chose qui ne nécessite pas de modification, vous pouvez utiliser les mêmes fonctions.

Si vous souhaitez annexer à un fichier à maintes reprises, cela entraîne des frais généraux considérables, mais cela est possible, comme illustré ici. En pratique, vous finissez normalement d'apporter des modifications à un tampon, manuellement ou par programmation, avant d'écrire dans un fichier (combinez simplement les deux premières expressions S dans l'exemple ci-dessous).

(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] Au moins, je n’irais pas jusqu’à appeler cela un système d’exploitation; une interface utilisateur alternative oui, un OS non.

[2] Vous ne pouvez charger que des parties d'un fichier, mais cela ne peut être spécifié que par octets.

[3] Un tampon est à la fois un type de données similaire à une chaîne et le "contenu visible lors de la modification d'un fichier". Lors de la modification, un tampon est affiché dans une fenêtre, mais les tampons ne doivent pas nécessairement être visibles pour l'utilisateur.

Éditer: Si vous voulez voir le texte inséré dans le tampon, vous devez évidemment le rendre visible et dormir entre les actions. Étant donné qu'Emacs ne réaffiche normalement l'écran que lorsque vous attendez une entrée utilisateur (et que dormir ne signifie pas attendre en entrée), vous devez également forcer le réaffichage. Cela est nécessaire dans cet exemple (utilisez-le à la place du deuxième sexe); en pratique, je n'ai jamais eu à utiliser "redisplay" même une fois - alors oui, c'est moche mais ...

(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
tarsius

Fichiers de lot Windows - Version 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

Pour expliquer cette dernière horrible recherche de boucle, supposons qu’il n’y ait que du monde hello (newline) dans le fichier. Donc, il saute juste la première ligne et écho seulement la seconde.

Changelog

  • 2 - Les opposants, doivent mal interpréter les exigences ou ils ont changé sur moi. Lit maintenant la dernière ligne du fichier

11
TheLQ

Scala:

Utilisation de la bibliothèque standard:

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)

Utiliser Josh Suereth Scala-ARM Library :

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)      


Étant donné que de nombreuses personnes ont utilisé le même descripteur de fichier pour écrire les deux chaînes, je l'inclue également dans ma réponse.

Utilisation de la bibliothèque standard:

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)

Utiliser Josh Suereth Scala-ARM Library :

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
missingfaktor

Sensationnel

new File("fileio.txt").with { 
    write  "hello\n"
    append "world\n"   
    println secondLine = readLines()[1]
}
11
Wayne Keenan
Rebol []

write/lines %fileio.txt "hello"
write/lines/append %fileio.txt "world"
print last read/lines %fileio.txt
10
Graham Chiu

Pour des exemples sur la manière de faire ce genre de choses dans beaucoup de langues (61!), Essayez la page sur File I/O à Rosetta Code). . Pour être juste, cela ne semble pas répondre exactement à ce que vous demandez - il s’agit d’entrées/sorties entières -, mais il est assez étroit et couvre un éventail plus large que ce que cette question risque d’attirer.

9
Donal Fellows

Delphes

Delphi, la méthode standard de bas niveau (c’est-à-dire sans TStringList et autres jouets):

program Project1;

{$APPTYPE CONSOLE}

uses
  SysUtils;

var
  f: Text;
  fn: string;
  ln: string;

begin

  fn := ExtractFilePath(ParamStr(0)) + 'fileio.txt';

  // Create a new file
  FileMode := fmOpenWrite;
  AssignFile(f, fn);
  try
    Rewrite(f);
    Writeln(f, 'hello');
    Writeln(f, 'world');
  finally
    CloseFile(f);
  end;

  // Read from the file
  FileMode := fmOpenRead;
  AssignFile(f, fn);
  try
    Reset(f);
    Readln(f, ln);
    Readln(f, ln);
    Writeln(ln);
  finally
    CloseFile(f);
  end;

end.

Comme Delphi est un compilateur Win32 natif, vous pouvez également utiliser l'API Windows pour gérer toutes les opérations d'E/S:

program Project1;

{$APPTYPE CONSOLE}

uses
  SysUtils, Windows;

var
  f: HFILE;
  fn: string;
  lns: AnsiString;
  fsize, amt, i: cardinal;
  AfterLine1: boolean;

const
  data = AnsiString('hello'#13#10'world');

begin

  fn := ExtractFilePath(ParamStr(0)) + 'fileio.txt';

  f := CreateFile(PChar(fn), GENERIC_WRITE, 0, nil, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  try
    WriteFile(f, data, length(data), amt, nil);
  finally
    CloseHandle(f);
  end;

  f := CreateFile(PChar(fn), GENERIC_READ, 0, nil, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  try
    fsize := GetFileSize(f, nil);
    SetLength(lns, fsize);
    ReadFile(f, lns[1], fsize, amt, nil);
    for i := 1 to fsize do
      case lns[i] of
        #10: AfterLine1 := true;
      else
        if AfterLine1 then
          Write(lns[i]);
      end;
  finally
    CloseHandle(f);
  end;


end.

Et, pour être complet, j'inclus l'approche de haut niveau, même si je ne l'utilise jamais moi-même:

program Project1;

{$APPTYPE CONSOLE}

uses
  SysUtils, Classes;

var
  fn: string;

begin

  fn := ExtractFilePath(ParamStr(0)) + 'fileio.txt';

  with TStringList.Create do
    try
      Add('hello');
      Add('world');
      SaveToFile(fn);
    finally
      Free;
    end;

  with TStringList.Create do
    try
      LoadFromFile(fn);
      Writeln(Strings[1]);
    finally
      Free;
    end;

end.
9
Andreas Rejbrand

Perl 6

use v6;

my $path = 'fileio.txt';

# Open $path for writing.
given open($path, :w) {
    .say('hello'); # Print the line "hello\n" to it.
    .close; # Close the file.
}

# Open the file for appending.
given open($path, :a) {
    .say('world'); # Append the line "world\n" to it.
    .close;
}

my $line = lines($path)[1]; # Get the second line. lines returns a lazy iterator.
say $line; # Perl 6 filehandles autochomp, so we use say to add a newline.

EDIT : voici une solution alternative avec une petite fonction d'assistance pour éviter la nécessité de fermer explicitement le fichier.

use v6;

sub with-file($path, *&cb, *%adverbs) {
    given open($path, |%adverbs) {
        .&cb;
        .close;
    }
}

my $path = 'fileio.txt';

# Open $path for writing.
with-file $path, :w, {
    .say('hello'); # Print the line "hello\n" to it.
};

# Open the file for appending.
with-file $path, :a, {
    .say('world'); # Append the line "world\n" to it.
};

my $line = lines($path)[1]; # Get the second line. lines returns a lazy iterator.
say $line; # Perl 6 filehandles autochomp, so we use say to add a newline.
8
ekiru

Prolog

% read_line_to_codes is defined in YAP library already.
% Uncomment the next line and remove the makeshift replacement definition to use it.
% use_module(library(readutil)).

readcodes(Stream,[]) :- peek_char(Stream,'\n'),get_char(Stream,'\n');peek_char(Stream,end_of_file).
readcodes(Stream,[First|Rest]) :- get_code(Stream,First),readcodes(Stream,Rest).

read_line_to_codes(Stream,Line) :- readcodes(Stream,Line),!.

:- open('fileio.txt',write,Stream),write(Stream,'hello\n'),close(Stream).
:- open('fileio.txt',append,Stream),write(Stream,'world'),close(Stream).

secondline(L) :- open('fileio.txt',read,Stream),read_line_to_codes(Stream,_),read_line_to_codes(Stream,L),close(Stream).
:- secondline(L),format('~s\n',[L]).
8
artificialidiot

Facteur

Pour plus d'informations (et pour télécharger la dernière version):

http://www.factorcode.org .

USING: io io.encodings.utf8 io.files ;

"fileio.txt" utf8
[ [ "hello" print ] with-file-writer ]
[ [ "world" print ] with-file-appender ]
[ file-lines last print ] 2tri
8
mrjbq7

ActionScript 3.0

Utilisation des bibliothèques Adobe AIR:

import flash.filesystem.File;
import flash.filesystem.FileMode;
import flash.filesystem.FileStream;

public class fileio
{
    public static function doFileIO():void
    {
        var file:File = File.applicationStorageDirectory.resolvePath("fileio.txt");
        var stream:FileStream = new FileStream();
        stream.open(file, FileMode.WRITE);
        stream.writeUTFBytes("hello");
        stream.writeUTFBytes("\nworld");
        stream.close();

        stream.open(file, FileMode.READ);
        var content:String = stream.readUTFBytes(stream.bytesAvailable);
        stream.close();
        var input:String = content.split("\n")[1];
        trace(input);
    }
}

Les applications AIR ne peuvent pas écrire dans leur répertoire pour des raisons de sécurité. Elles utilisent donc le répertoire de stockage de l'application.

8
alxx

ANSI C (API POSIX)

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

#include <stdio.h> /* For error reporting */

#define BUFFER_SIZE 6

int main (int argc, char *argv[])
{
    int fd;
    const char HELLO[] = "hello\n";
    const char WORLD[] = "world\n";

    if ((fd = open ("fileio.txt", O_RDWR | O_CREAT | O_TRUNC, S_IRWXU)) < 0) {
        perror ("open");
        return 1;
    }

    if (write (fd, HELLO, sizeof (HELLO)) < 0) {
        perror ("write");
        return 1;
    }

    if (write (fd, WORLD, sizeof (WORLD)) < 0) {
        perror ("write(2)");
        return 1;
    }

    /* Rewind file */
    lseek (fd, 0, SEEK_SET);

    /* Read whole file */
    int bytes_read;
    do {
        char buffer[BUFFER_SIZE];

        bytes_read = read (fd, buffer, BUFFER_SIZE);
        write (0, buffer, bytes_read);
    } while (bytes_read > 0);


    if (close (fd) != 0) {
        perror ("close");
        return 1;
    }

    return 0;
}
7
el.pescado

* NIX Shell (bash ou sh)

#!/bin/bash

echo 'hello' > fileio.txt
echo 'world' >> fileio.txt

myvar=`tail -n 1 fileio.txt`
echo $myvar
7
Chinmay Kanchi

Lua

io.open( 'TestIO.txt', 'w' ):write( 'hello' ):write( '\n', 'world' ):close()
aLine = io.open( 'TestIO.txt', 'r' ):read( '*a' ):match( '%C*%c*(.*)' )
print( aLine )
7
Petite Abeille

Tcl

set f [open fileio.txt w+]

puts $f hello    
puts $f world

seek $f 0

puts [lindex [split [read $f] \n] 1]

close $f
7
Tcl

Io

File with("fileio.txt") open write("hello\n") write("world\n") \
    rewind readLines second println

Est-ce la plus courte des solutions?

7
Steve Dekorte

MUMPS (non obscurci)

Pour des raisons historiques liées à l'espace disque et à l'utilisation de la mémoire, ca. 1969, MUMPS vous permet de tronquer les commandes en un (ou parfois deux) caractères, c’est pourquoi l’exemple de Clayton est si "étrange" (bien que je puisse le lire assez facilement). En savoir plus sur ce qui se passe avec ce programme MUMPS.

FileIo ; Define a "label" identifying this piece of code (not a function here).
 ; MUMPS has only process-specific variable scope, so stack local
 ; variables with the 'New' command.
 New File, Line1, Line2
 Set File="FILEIO.TXT"

 ; MUMPS has a concept of a "currently open" device, which "Read" and "Write"
 ; commands use.  Identify a device with the Open command and switch to the
 ; device with the "Use" command.  Get rid of the device with the "Close"
 ; command.

 ; Another funny thing here is the "postconditional expression," which in this
 ; case is "WNS".  In this case we pass arguments to the Open command.  The
 ; exact meaning is implementation-specific but if I had to guess, these
 ; arguments have to do with opening the file for writing, using a newline
 ; character as a delimiter, etc.
 Open File:"WNS" Use File Write "hello" Close File
 Open File:"WAS" Use File Write !,"world" Close File ; ! = new line

 ; Here the "Read" command executes twice on the file, reading two lines into
 ; the variables "Line1" and "Line2".  The Read command is probably aware of the
 ; line-oriented nature of the file because of the "RS" postconditional.
 Open File:"RS" Use File Read Line1,Line2 Close File Write Line2,!
 Quit
6
Sean Woods

D avec Tango

import tango.text.Util, tango.io.Stdout, tango.io.device.File;

void main()
{
    scope file = new File ("fileio.txt", File.ReadWriteCreate);
    file.write ("hello\n");
    file.write ("world\n");
    auto line = splitLines (file.rewind.text())[1];
    stdout(line).nl;
}

Version condensée:

void main()
{
        with (new File ("fileio.txt", File.ReadWriteCreate))
              stdout (lineOf (put("hello\n").put("world\n").rewind.text(), 1)).nl;    
}
6
doh

C # avec Streams

Un bon exemple C # avait déjà été fourni précédemment, mais j’ai pensé qu’il serait également utile de savoir comment effectuer des entrées/sorties sur des fichiers ligne par ligne avec des flux.

        string path = @"fileio.txt";

        //creating file and writing to it
        using (StreamWriter writer = File.CreateText(path))
        {
            writer.WriteLine("Hello");
        }

        //appending to existing file
        using (StreamWriter writer = File.AppendText(path))
        {
            writer.WriteLine("World");
        }

        //reading file
        using(StreamReader reader = File.OpenText(path))
        {
            int lineNum = 0;
            string line = null;

            while ((line = reader.ReadLine()) != null)//read until eof
            {
                if (++lineNum == 2)
                {
                    Console.WriteLine(line);
                }
            }
        }
6
Judicium

Python 2


Exemple 1:

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

Exemple 2 - sans les gestionnaires de contexte:

f = open('fileio.txt', 'a')
f.write('hello')
f.write('\nworld')
f.close()
f = open('fileio.txt')
s = f.readlines()[1]
f.close()
print s
6
Corey Goldberg

Perl moderne

use 5.012;
use warnings;
use autodie;

# 1 & 2 - create and write line to file
open my $new, '>', 'fileio.txt';
say {$new} 'hello';
close $new;

# 3 - open file to append line 
open my $append, '>>', 'fileio.txt';
say {$append} 'world';
close $append;

# 4 - read in second line to input string
my $line = do {
    open my $read, '<', 'fileio.txt';
    <$read>;    # equivalent to: readline $read
    <$read>;    # last value expression gets returned from do{}
};

print $line;   # 5 - print input string!

Ci-dessus est un exemple élémentaire d'utilisation de open dans Modern Perl (c'est-à-dire trois poignées de fichiers lexicales, "open arg", lexique, autodie et meilleures pratiques).

Cependant, il est vraiment inutile de polluer l'espace de noms avec $new et $append variables lexicales (qui contiennent le descripteur de fichier). Donc, pour les points 1 à 3, je serais probablement plus heureux de faire:

{ 
    open my $fh, '>', 'fileio.txt';
    say {$fh} 'hello';
}

{ 
    open my $fh, '>>', 'fileio.txt';
    say {$fh} 'world';
}

ou:

use IO::File;   # core module

IO::File->new( 'fileio.txt', 'w' )->print( "hello\n" );
IO::File->new( 'fileio.txt', 'a' )->print( "world\n" );


Mise à jour Objet: clarification: Il n'est pas nécessaire de rouvrir le fichier texte après avoir écrit la première ligne

Et aucune mention si vous avez besoin de rouvrir le fichier pour relire la deuxième ligne, donc tout peut se faire comme suit:

my $line = do {
    open my $fh, '+>', 'fileio.txt';
    say {$fh} $_ for qw/hello world/;  # or just: say {$fh} "hello\nworld" :)
    seek $fh, 0, 0;                    # rewind to top of file
    (<$fh>)[1];                        # no need to be lazy with just 2 recs!
};

print $line;

/ I3az /

6
draegtun

Fortran

Je déteste le FORTRAN récemment, alors voici:

      PROGRAM FILEIO
C     WRITES TWO LINES TO A TEXT FILE AND THEN RETRIEVES THE SECOND OF
C     THEM
      CHARACTER*5 STRIN
      OPEN(UNIT=1, FILE='FILEIO.TXT')
      WRITE(1,100) 'HELLO'
      WRITE (1,100) 'WORLD'
      CLOSE(1)
C
      OPEN(UNIT=2, FILE='FILEIO.TXT')
      READ(2,100) STRIN
      READ(2,100) STRIN
      WRITE(*,*) STRIN
 100  FORMAT(A5)
      STOP
      END  

Edit by ldigas: Par contre, je l'aime plutôt
(désolé de jouer avec votre réponse; je n'avais pas envie de commencer un autre post Fortran)

character(10) :: line
open(1,file='fileio.txt',status='replace')
write(1,'("hello"/"world")'); rewind(1);
read(1,'(/a)')line; write(*,'(a)')line
end

(ceci est une variante un peu plus récente de Fortran ... seulement âgée de 15 à 20 ans; -)

6
JasonFruit

Visual Basic 6.

open "fileio.txt" for output as #1
write #1, "hello"
close #1

open "fileio.txt" for append as #1
write #1, "world"
close #1

open "fileio.txt" for input as #1
dim strn as string
input #1, strn
input #1, strn
msgbox(strn)
close #1
6
Mark Bell

Python

open('fileio.txt', 'w').write('hello\n')
open('fileio.txt', 'a').write('world\n')
with open('fileio.txt', 'r') as f:
  print f.readline() and f.readline(),
5
OTZ

Io

f := File with("fileio.txt")
f open
f write("hello")
f close

f openForAppending
f write("\nworld")
f close

f openForReading
secondLine := f readLines at(1)
f close
write(secondLine)
5
Ionuț G. Stan

JScript (hôte de script Windows)

var fileName = "fileio.txt";
var ForReading = 1;
var ForAppending = 8;

var fso = new ActiveXObject("Scripting.FileSystemObject")

// Create a file and write to it
var file = fso.CreateTextFile(fileName, true /* overwrite if exists */);
file.WriteLine("hello");
file.Close();

// Append to the file
file = fso.OpenTextFile(fileName, ForAppending);
file.WriteLine("world");
file.Close();

// Read from the file
file = fso.OpenTextFile(fileName, ForReading);
file.SkipLine();
var str = file.ReadLine();
file.Close();
WScript.Echo(str);
5
Helen

J

f =: 'fileio.txt'
('hello', LF) 1!:2 < f
('world', LF) 1!:3 < f
; 1 { < ;. _2 (1!:1  < f)

La dernière ligne lit le fichier (1!:1 < f), le découpe en lignes (< ;. _2), obtient le deuxième élément (1 {). Puis le monadique ; est utilisé pour déballer l'élément.

5
Bertrand Marron

Pascal

 Program pascalIO;
    Var FName, TFile  : String[15];
        UserFile: Text; 
    Begin
     FName := 'fileio.txt';
     Assign(UserFile, FName);  
     Rewrite(UserFile);  
     Writeln(UserFile,'hello');
     Writeln(UserFile,'world');
     Close(UserFile);

     Assign(UserFile, FName);
     Reset(UserFile);
     Readln(UserFile,TFile);
     Readln(UserFile,TFile);
     Writeln( TFile);


     Close(UserFile);
    End.
5
Mite Mitreski

K 3

f:`fileio.txt
f 0:/:(*a;a:$`hello`world)
`0:*1_0:f
4
kevinlawler

JavaScript - Narwhal sur Node

var FS = require("narwhal/fs");
FS.open("fileio.txt", "w")
    .print("hello")
    .print("world")
    .close()

var stream = FS.open("fileio.txt", "r");
stream.next();
print(stream.next());
stream.close();

Ceci est une autre incorporation JavaScript particulière.

http://narwhaljs.org

4
Kris Kowal

AWK

(sans retour en ligne de commande)

BEGIN {
    print "hello" > "fileio.txt"
    print "world" > "fileio.txt"
    for ( i = 0; i < 2; i ++ )
        getline < "fileio.txt"
    fflush( "fileio.txt" );

    print $0
}
4
Potatoswatter

Clojure

Parce que vous voulez lire ligne par ligne, vous ne pouvez pas utiliser Slurp, donc

(use 'clojure.Java.io)

Et puis dans le style LISP traditionnel:

(let [f "hello.txt"]
  (spit f "hello\n") 
  (spit f "world\n" :append true)
  (print (second (line-seq (reader f)))))

ou, dépourvu de crochets bien-aimés:

(doto "hello.txt"
  (spit "hello\n")
  (spit "world\n" :append true)
  (-> reader line-seq second print ))
4

Raquette PLT

#lang racket
(call-with-output-file "fileio.txt"
                       #:exists 'truncate
                       (lambda (out)
                            (fprintf out "hello\n" )))
(call-with-output-file "fileio.txt"
                       #:exists 'append
                       (lambda (out)
                            (fprintf out "world\n" )))
(call-with-input-file "fileio.txt"
                      (lambda (in)
                            (read-line in)
                            (display (read-line in))))
4
Jason Baker

Ioke

path = "fileio.txt"

FileSystem withOpenFile(path, fn(f,
    f println("hello"))
)
FileSystem withOpenFile(path, fn(f,
    f println("world"))
)
FileSystem readLines(path) [1] print
4
Ionuț G. Stan

[~ # ~] caos [~ # ~]

(le langage de script pour le moteur de jeu Creatures )

* Open fileio.txt for output (non-append) in global directory
FILE OOPE 0 "fileio.txt" 0
OUTS "hello\n"
OUTS "world\n"
* Close file
FILE OCLO

* Open file for read
FILE IOPE 0 "fileio.txt"
SETS VA00 INNL * read line
SETS VA00 INNL * read line
DBG: OUTS VA00 * print to debug console
FILE ICLO
3
bdonlan

Python 2 (solution alternative)

with open('fileio.txt','w') as f:
    print>>f,'hello' #write
    print>>f,'world'
with open('afile.txt','r') as f:
    s = f.readlines()[1] #read
    print s
3
Chinmay Kanchi

MATLAB

Utilisation de routines de bas niveau fopen/fclose/fseek/fscanf/etc

% read a integers from a file... 

file = fopen('filename', 'r'); // read only 

if (file == -1) 
  error('file can''t be read'); 
end 

[number, count] = fscanf(file, '%d', 1); 

while (count == 1)
  fprintf('read %d\n', number); 
  [number, count] = fscanf(file, '%d', 1); 
end 

fclose(file);

En utilisant des routines de haut niveau, chargez/sauvegardez/textscan/uigetfile/etc

% Load and store a matrix 
M = load('sample_file.txt') 

save filename M
3
pmod

Huer

import System.IO
path = "fileio.txt"
File.WriteAllText(path, "hello")
File.AppendAllText(path, "\nworld")

secondLine = File.ReadAllLines(path)[1]
print secondLine
3
st0le

OREILLONS

FILEIO ;
 N F,L1,L2
 S F="FILEIO.TXT"
 O F:"WNS" U F W "hello" C F
 O F:"WAS" U F W !,"world" C F
 O F:"RS" U F R L1,L2 C F W L2,!
 Q
3
Clayton

Arc

Soumission originale:

(w/stdout (outfile "fileio.txt")
  prn!hello
  prn!world)
(pr:cadr:readfile "fileio.txt")

Il a été souligné que cela ne répondait pas aux exigences de l'ajout de la deuxième ligne (plutôt que de l'écrire en continu). waterhouse corrige cela et apporte d'autres améliorations dans sa version:

(w/outfile f "fileio.txt"
  (disp "hello\n" f))
(w/appendfile f "fileio.txt"
  (disp "world\n" f))
(pr:cadr:readfile "fileio.txt")

Mise à jour: Cette dernière révision répond aux préoccupations éventuelles concernant la non-lecture du mot "monde" dans une variable:

(w/outfile f "fileio.txt"
  (disp "hello\n" f))
(w/appendfile f "fileio.txt"
  (disp "world\n" f))
(w/infile f "fileio.txt"
  (repeat 2 (= l readline.f))
  (prn l))
3
evanrmurphy

Coldfusion

Créez un nouveau fichier texte appelé "fileio.txt". Écrivez la première ligne "hello" dans le fichier texte.

 <cffile action="Write" file="fileio.txt" output="hello">  

Ajoutez la deuxième ligne "monde" au fichier texte.

<cffile action="Append" file="fileio.txt" output="world"> 

Lire la deuxième ligne "world" dans une chaîne d'entrée. Imprimer la chaîne d'entrée sur la console.

 <cffile action="read" file="fileio.txt" variable="filecontents">
 <cfoutput>#ListLast(filecontents,Chr(13) & Chr(10))#</cfoutput>
3
Brian Bolton

Progress OpenEdge ABL

DEFINE VARIABLE cString AS CHARACTER NO-UNDO.

OUTPUT TO VALUE("fileio.txt").
PUT UNFORMATTED "hello" SKIP.
OUTPUT CLOSE.

OUTPUT TO VALUE("fileio.txt") APPEND.
PUT UNFORMATTED "world" SKIP.
OUTPUT CLOSE.

INPUT FROM VALUE("fileio.txt").
/* Read each line in to cString; at the end of the loop */
/* the variable will contain the last line of the file. */
REPEAT:
  IMPORT UNFORMATTED cString.
END.
INPUT CLOSE.

MESSAGE cString.
2
Abe Voelker

niVerse BASIC/UniData UniBASIC

* UFD is the 'User File Directory' in this account
* This may be called &UFD& in UniVerse
OPEN 'UFD' TO F.UFD ELSE
  CRT 'CANNOT OPEN UFD'
  STOP
END

* Write to file
REC = ''
REC<1> = 'Hello'
REC<2> = 'World'
* When writing to a filesystem, each attribute of a dynamic array is stored
* as a separate line in the file.  When writing to a hashed file (aka, table)
* each attribute is stored separated by a field mark.
WRITE REC TO F.UFD,'fileio.txt'

* Read from file
REC = ''
READ REC FROM F.UFD,'fileio.txt' ELSE
  CRT 'CANNOT READ RECORD'
  STOP
END
CRT REC<2>

Il existe d'autres moyens de procéder, tels que l'utilisation d'un fichier séquentiel (OPENSEQ/READSEQ/WRITESEQ/CLOSESEQ). C'est un moyen facile de le faire car le fichier est traité comme n'importe quel autre enregistrement.

2
Dave

Petit basique

path = "c:\fileio.txt"
File.WriteLine(path, 1, "Hello")  'write the first line
File.WriteLine(path, 2, "World")  'write the second line
stuff = File.ReadLine(path, 2)    'read the second line
TextWindow.WriteLine(stuff)
2
David Hoerster

AWK

BEGIN {
  print "hello" > "fileio.txt"
  print "world" > "fileio.txt" # subsequent writes to the same output file append to it
  close("fileio.txt")
}

/world/ { print $0 }

Pour exécuter le script

$ awk -f script.awk fileio.txt
2
helpermethod

Classic ASP/VBScript

Je sais que cela est en train de disparaître mais, meh!

Vous pouvez utiliser le paramètre facultatif create de openTextFile pour créer un fichier texte non existant, mais je vous ai montré le chemin le plus long.

Ceci n’a pas été testé mais devrait fonctionner correctement.

<%
Option Explicit

Dim objFso
Dim ourFile
Dim strFilePath
Dim strLine

strFilePath = Map("fileIO.txt")     
Set objFso = CreateObject("Scripting.FileSystemObject")

'Create text file, add hello line
Set ourFile = objFso.CreateTextFile(strFilePath)    
ourFile.WriteLine("hello")
ourFile.close

'Append world to a newline
Set ourFile = objFso.OpenTextFile(strFilePath, ForWriting) 
ourFile.writeline("world")
ourFile.close

'Read lines
Set ourFile = objFso.OpenTextFile(strFilePath, ForReading)
ourFile.skipLine
strLine = ourFile.readLine
ourFile.close

'Print value
response.write(strLine)

'Clean up this shiz
Set ourFile = nothing
Set objFso = nothing
%>
2
Tom Gullen

VBScript

Adapté de Helen's Answer pour JScript.

fileName = "fileio.txt"
Set fso = CreateObject("Scripting.FileSystemObject")

Set file = fso.CreateTextFile(fileName, true)
file.WriteLine("hello")
file.WriteLine("world")
file.Close()

ForReading = 1
Set file = fso.OpenTextFile(fileName, ForReading,false)
file.SkipLine()
WScript.Echo(file.ReadLine())
'Msgbox(file.ReadLine()) 'same as above
file.Close()
2
st0le

Icône

procedure main(args)
   f:=open("fileio.txt","w")
   write(f,"hello")
   close(f)

   f:=open("fileio.txt","a")
   write(f,"world")
   close(f)

   f:=open("fileio.txt","r")
   line:=(!f & !f)
   # or you can use
   # every 1 to 2 do line:=!f       
   close(f)
   write(line)
end
2
artificialidiot

Python 3

Cela diffère de l'autre version en utilisant print pour toutes les sorties et en ouvrant le fichier une seule fois.

with open('fileio.txt', 'w+') as f:
    print('hello', file=f)
    pos = f.tell()
    print('world', file=f)
    f.seek(pos)
    s = f.read()
    print(s)
2
dan04

SAS

data; 
file 'c:\fileio.txt'; 
put 'hello' /  'world';

data;
infile 'c:\fileio.txt'; 
input /; 
put _infile_;
1
tedc

Java Me

public static void writeFile(String fileName, String data) {
        FileConnection fconn = null;
        OutputStream os = null;
        try {
            String fName = "file:///SDCard/" + fileName;
            fconn = (FileConnection) Connector
                    .open(fName, Connector.READ_WRITE);
            if (!fconn.exists()) {
                fconn.create();
            }
                  //for append use following line
                  //os = fconn.openOutputStream(fconn.fileSize());
                    os = fconn.openOutputStream();
            os.write(data.getBytes());
        } catch (Exception e) {
            System.out.println("Output file error: " + e.getMessage());
        } finally {
            try {
                os.close();
                fconn.close();
            } catch (IOException e) {
                System.out.println(e.getMessage());
            }

        }

    }

private static byte[] readFile(String fileName) {
        String fName = "file:///SDCard/" + fileName;
        byte[] data = null;
        FileConnection fconn = null;
        DataInputStream is = null;
        try {
            fconn = (FileConnection) Connector.open(fName, Connector.READ);
            is = fconn.openDataInputStream();
            byte b[] = new byte[1024];
                        int length = is.read(b, 0, 1024);
                        System.out.println("Content of "+fileName + ": "+ new String(b, 0, length));
        } catch (IOException e) {
            System.out.println(e.getMessage());
        } finally {
            try {
                if (null != is)
                    is.close();
                if (null != fconn)
                    fconn.close();
            } catch (IOException e) {
                System.out.println(e.getMessage());
            }
        }
        return data;
    }
1
Vivart

Aller

// Disclaimer: I did this mostly because it sounded like a fun quick
// hack, I don't normally use Go at all.
// Using log.Exit like this is probably horrible style.

package main

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

func OpenFile(mode int) *os.File {
    f, err := os.Open("fileio.txt", mode, 0644)
    if err != nil {
        log.Exit(err)
    }
    return f
}

// Create an interface just for fun, since it'll be satisfied
// automatically by bufio's Reader.
type HasReadString interface {
    ReadString(b byte) (string, os.Error)
}

func ReadLine(r HasReadString) string {
    l, err := r.ReadString('\n')
    if err != nil {
        log.Exit(err)
    }
    return l
}

func main() {
    f := OpenFile(os.O_CREAT | os.O_TRUNC | os.O_WRONLY)
    defer f.Close()
    f.WriteString("hello\n")
    f.WriteString("world\n")

    f = OpenFile(os.O_RDONLY)
    defer f.Close()
    r := bufio.NewReader(f)
    _ = ReadLine(r)
    fmt.Print(ReadLine(r))
}
1
durin42

La liste de liens en cours de la publication d'origine comporte quelques erreurs pour Arc. Voici la version corrigée:

<a href="http://arclanguage.org">Arc</a> - 
<a href="http://stackoverflow.com/questions/3538156/file-i-o-in-every-programming-language/3539940#3539940">evanrmurphy</a>

(Désolé d'ajouter une nouvelle réponse pour cette correction, mais ma réputation est insuffisante pour faire un commentaire. N'hésitez pas à l'enlever une fois que c'est corrigé. Merci.)

0
evanrmurphy