Чтение и запись в файл

Код решения для задачи B: чтение и запись в файл.

Выберите название компилятора (языка программирования):

Free Basic 1.04
Dim a As Long, b As Long, c As long
open "input.txt" For Input As #1
input #1,a
input #1,b
c=a+b
Open "output.txt" for Output As #2
Print #2, c
close 
GNU c 4.9
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
      int temp = 0, sum = 0;
      FILE * f = fopen("input.txt", "rt");
while ( fscanf(f, "%d", &temp) == 1 )
      sum += temp;
      fclose(f);
      FILE * o = fopen("output.txt", "w");
      fprintf(o, "%d", sum);
      fclose(o);
      return 0;
}   
Mono C# 5.2.0
using System.IO;

public class Test
{
    static void Main()
    {
        using (StreamReader sr = new StreamReader("input.txt"))
        {
            string[] array = sr.ReadLine().Split(' ');
            int a = int.Parse(array[0]);
            int b = int.Parse(array[1]); ;
            using (StreamWriter sw = new StreamWriter("output.txt"))
            {
                sw.WriteLine(a + b);
            }
        }
    }
}     
GNU C++ 4.9
#include <fstream>
  
  int main()
  {
  std::ifstream fin("input.txt");
  std::ofstream fout("output.txt");
  int a, b;
  fin >> a >> b;
  fout << a + b;
  return 0;
  }     
GNU C++ 11 4.9
#include<bits/stdc++.h>
  
  using namespace std;
  
  int main()
  {
  freopen("input.txt","r",stdin);
  freopen("output.txt","w",stdout);
    int a,b;
    cin>>a>>b;
    cout<<a+b;
    return 0;
    }    
GNU C++ 17 7.3
#include <iostream>
#include <fstream>
    using namespace std;
    int main(){
    ifstream cin("input.txt");
    ofstream cout("output.txt");
    long long a, b;
    cin >> a >> b;
    long long c = a+b;
    cout << c;
    }    
Dart 2.14.3
import 'dart:convert';
import 'dart:io';

Future<void> main() async {
  final inputFile = File('./input.txt');
  final outputFile = File('./output.txt').openWrite();

  Stream<String> lines = inputFile
      .openRead()
      .transform(utf8.decoder)
      .transform(const LineSplitter());

  await for (var line in lines) {
    final numbers = line.split(' ');
    final a = int.parse(numbers.first);
    final b = int.parse(numbers.last);

    outputFile.writeln(a + b);
  }

  await outputFile.close();
}
dmd
import std.stdio;
import std.algorithm;

void main() {
stdin = File("input.txt", "r");
stdout = File("output.txt", "w");
int a, b;
readf("%d %d", &a, &b);
writeln(a + b);
}  
Delphi 2.4.4
var a, b, c: longint;
begin
    assign(input,'input.txt');
    reset(input);
    assign(output,'output.txt');
    rewrite(output);
    read(a, b);
    c := a + b;
    writeln(c);
    close(input);
    close(output);
end.
gc go
package main

import ("fmt"; "os")

func main(){
    in, _ := os.Open("input.txt")
    out, _ := os.Create("output.txt")
    var a, b int
    fmt.Fscanf(in, "%d %d", &a, &b)
    fmt.Fprintf(out, "%d", a+b)
}     
gcc go
package main

import (
"fmt"
"os"
"strconv"
)

func main() {
var a, b int
f, _ := os.Open("input.txt")
defer f.Close()

fmt.Fscanf(f, "%d %d", &a, &b)

out, _ := os.Create("output.txt")
defer out.Close()

res := a + b
out.Write([]byte(strconv.Itoa(res)))
}      
Haskell 7.10.2
main = do
[x, y] <- map read . words <$> readFile "input.txt"
  writeFile "output.txt" $ show $ x + y 
Oracle Java 7
import java.io.*;

public class Main7 {
    public static void main(String[] args) {
        String s;
        String result = null;
        try (BufferedReader br = new BufferedReader(new FileReader("input.txt"))) {
            while ((s = br.readLine()) != null) {
                String[] arr = s.split(" ");
                Long a = Long.parseLong(arr[0]);
                Long b = Long.parseLong(arr[1]);
                result = String.valueOf(a + b);
                System.out.println(s);
            }
        } catch (IOException ex) {

            System.out.println(ex.getMessage());
        }

        try (BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"))) {

            bw.write(result);
        } catch (IOException ex) {

        System.out.println(ex.getMessage());
        }
    }
}     
Oracle Java 8
import java.io.*;
public class Main
{
    public static void main(String[] args) throws Exception
    {
        StreamTokenizer in = new StreamTokenizer(
            new BufferedInputStream(
                new FileInputStream(new File("input.txt"))));
        PrintStream out = new PrintStream(new File("output.txt"));
        int a, b;
        in.nextToken();
        a = (int) in.nval;
        in.nextToken();
        b = (int) in.nval;
        out.println(a + b);
    }
}
Kotlin 1.3.50 (JRE 1.8.0)
import java.io.*

fun main(args: Array<String>) {
  val input = BufferedReader(FileReader("input.txt"))
  val output = BufferedWriter(FileWriter("output.txt"))
  
  val numberStrings = input.readLine()!!.split(" ")
  output.write((numberStrings[0].toInt() + numberStrings[1].toInt()).toString())
  output.flush()
  }
OpenJDK Java 11 x64
import java.io.*;

public class Yandex {
    public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(new FileReader("input.txt"));
        String file = reader.readLine();
        String[] nums = file.split(" ");
        int sum = 0;
        for (int i = 0; i < nums.length; i++) {
            sum += Integer.parseInt(nums[i]);
        }
        FileWriter writer = new FileWriter("output.txt");
        writer.write(String.valueOf(sum));
        writer.flush();
    }
}   
Node JS 8.16
const fs = require('fs')
let fileContent = fs.readFileSync("input.txt", "utf8");

const [a, b] = fileContent.toString().split(' ')

const result = Number(a) + Number(b)

fs.writeFileSync("output.txt", result.toString())
ocaml 4.02.3
let ifname = "input.txt" in
let ofname = "output.txt" in
let inch = open_in ifname in
let str = input_line inch in
let sum = Scanf.sscanf str "%d %d" (fun a b -> a + b) in
let outch = open_out ofname in
Printf.fprintf outch "%d\n" sum;
close_in inch;
flush outch;
close_out outch;;
Swift 4.1.1
import Foundation

let fileName = "input.txt"

func readNums() {
guard let line = try? String(contentsOfFile: fileName) else {
return
}
let split = line.split(separator: "\n")
guard split.count == 1 else {
return
}
let nums = split[0].split(separator: " ")
guard nums.count == 2, let a = Int(nums[0]), let b = Int(nums[1]) else {
return
}
let result = String(a + b)
try? result.write(toFile: "output.txt", atomically: true, encoding: .utf8)
}

readNums()
Free pascal 2.4.4
var x,y:longint;
t,t2:text;
begin
assign(t,'input.txt');
reset(t);
read(t,x,y);
close(t);
assign(t2,'output.txt');
rewrite(t2);
writeln(t2,x+y);
close(t2);
end.
PascalABC.NET 3.5.1
var a,b,c : integer;
f1,f2 : text;
begin
assign(f1,'input.txt');
assign(f2,'output.txt');
reset(f1);
rewrite(f2);
//while(not eof(f1)) do
begin
readln(f1,a,b);
c:=a+b;
writeln(f2,c);
end;
close(f1);
close(f2);
end.     
Perl 5.14
open(FH, '<', 'input.txt') or die $!;
my ($f, $s) = split(' ', <FH>);
          
close FH;
          
open(OF, '>', 'output.txt') or die $!;
print OF ($f + $s);
close OF;
php 5.3.10
<?php

$input = fopen('input.txt', 'r') or die("не удалось открыть файл");
$str = fgets($input);
$arr = explode(" ", $str);

$output = fopen("output.txt", 'w') or die("не удалось открыть файл");
$result = $arr[0] + $arr[1];
fwrite($output, "".$result);

fclose($inputstr);
fclose($output);

?>   
php 7.3.5
<?
// input
function getInputData($file = 'input.txt') {
    $data = [];
    $fh = fopen($file,'r');
    while ($line = fgets($fh)) {
         $data[] = $line;
    }
    fclose($fh);

    return $data;
}

$input = getInputData();
$numbers = explode(' ', $input[0]);
$result = 0;
foreach ($numbers as $number) {
    $result += $number;
}

//echo $result;
file_put_contents('output.txt', $result);
pypy 4
with open('input.txt', 'r') as fin:
    a, b = map(int, fin.readline().strip().split())
with open('output.txt', 'w') as fout:
    c = str(a+b)
    fout.write©
Python 2.7
num1, num2 = (open("input.txt", "r").read()).split()
resu = open("output.txt","w")
resu.write(str(int(num1) + int(num2)))
Python 3.6
reader = open('input.txt', 'r')
a, b = [int(n) for n in reader.readline().split(" ")]
reader.close()

writer = open('output.txt', 'w')
writer.write("%d" % (a+b))
writer.close()
R
A=scan("input.txt",sep=" ")
write(A[1]+A[2],file="output.txt")
Ruby 1.9.3
f_o = File.new('output.txt', 'w')
File.open('input.txt', 'r') do |f_i|
a,b = f_i.readline.split.map(&:to_i)
  f_o.puts a+b
end
Ruby 2.2.3
string = File.open('input.txt', 'rb').read
          a, b = string.split(' ').map(&:to_i)
File.open('output.txt', 'w') { |file| file.write(a + b) }
rust 1.2
use std::io::prelude::*;
use std::fs::File;

fn main() {
  let mut file = File::open("./input.txt").unwrap();
 let mut buffer = String::new();
 file.read_to_string(&mut buffer);
  let split_buffer = buffer.split_whitespace();
  let mut result: i32 = 0;
  for item in split_buffer {
  result += item.parse::<i32>().unwrap();
  }
    
  let mut resultToStr = format!("{}", result);
  let mut out = File::create("./output.txt").unwrap();
  out.write_all(&mut resultToStr.as_bytes()).unwrap();
}
Scala 2.9.1
import scala.io.Source
import java.io._

object hello extends App {
  //println(readLine().split(' ').toList.map(_.toInt).foldRight(0){(z, i) => z + i})
  val file = new File("output.txt")
  val bw = new BufferedWriter(new FileWriter(file))
  val filename = "input.txt"
  for (line <- Source.fromFile(filename).getLines) {
    bw.write(line.split(' ').toList.map(_.toInt).foldRight(0){(z, i) => z + i}.toString)
  }
  bw.close()
}        
GNU bash 4.2.24
read a b <input.txt;echo $(($a+$b))>output.txt
        
Написать в службу поддержки