11
votes
\$\begingroup\$

The challenge:

Input text from one file and output it to another. Solution should be a complete, working function.

Note: This is a question. Please do not take the question and/or answers seriously. More information here.

\$\endgroup\$
1
  • \$\begingroup\$ Code-trolling is in the process of being removed, as per the official stance. This question has a fair amount of votes with one extremely highly voted answer. It recieved just slightly over 50% "delete" votes on the poll, but only by about 8%, so I am locking it for historical significance. \$\endgroup\$
    – Doorknob
    Commented May 12, 2014 at 12:46

22 Answers 22

38
votes
\$\begingroup\$

C

The whole point of having multiple programming languages, is that you need to use the right tool for the job.
In this case, we want to copy bytes from one file to another.
While we could use something fancy like bash or ruby, or fall to the power of ASM, we need something quick, good with bits and fast.
The obvious choice is C.
The SIMPLEST way of doing it would be like so:

#include <stdio.h>
#define THEORY FILE
#define AND *
#define PRACTICE myfile1
#define SOLUTIONS myfile2
#define ARE fopen
#define IMPORTANT "r"
#define BAD "w"
#define LOL fclose
#define PLEASE fgetc
#define HELP fputc
#define ME return
#define NEVER for
#define SURRENDER !=
#define VERY filename1
#define NOT filename2
#define _ 1

int copyFile(char* filename1, char* filename2)
{
  THEORY AND PRACTICE = ARE (VERY, IMPORTANT);
  THEORY AND SOLUTIONS = ARE (NOT, BAD);
  NEVER (;_;)
  {
    HELP(PLEASE(PRACTICE),SOLUTIONS);
  }
  ME _SURRENDER_;
}

This is evil because it will read garbage on things like cygwin, is completely chinese for a beginner, will scare him when he realizes it's a call for help and, obviously, because C.

\$\endgroup\$
11
  • 8
    \$\begingroup\$ #define VERY filename1 #define NOT filename2 \$\endgroup\$
    – Joe Z.
    Commented Dec 28, 2013 at 5:01
  • 1
    \$\begingroup\$ Changed those defs for you. I kept them the same on the function declaration for MORE confusion! \$\endgroup\$
    – user11485
    Commented Dec 28, 2013 at 5:04
  • 8
    \$\begingroup\$ Also, if you #define _ 1, you can make (;_;) with the for-loop, to make it look like a smiley. \$\endgroup\$
    – Joe Z.
    Commented Dec 28, 2013 at 5:14
  • 5
    \$\begingroup\$ #define LOL fclose made my day \$\endgroup\$
    – thwd
    Commented Dec 28, 2013 at 13:04
  • 1
    \$\begingroup\$ #define LOL fclose, which is never used is my masterpiece though. \$\endgroup\$
    – user11485
    Commented Jan 17, 2014 at 15:41
26
votes
\$\begingroup\$

sh

I like the simplicity of this one.

echo File1.txt > File2.txt

Really only works properly if File1.txt contains "File1.text"...

\$\endgroup\$
11
  • \$\begingroup\$ What is wrong with it? \$\endgroup\$
    – user10766
    Commented Dec 28, 2013 at 4:25
  • 4
    \$\begingroup\$ @user2509848 It puts the text "File1.txt" into File2.txt, not the actual contents of File1.txt \$\endgroup\$
    – syb0rg
    Commented Dec 28, 2013 at 4:35
  • \$\begingroup\$ But this doesn't actually cheat the question... \$\endgroup\$
    – jeremy
    Commented Dec 28, 2013 at 4:49
  • 1
    \$\begingroup\$ Could just as well be sh as there isn't anything bash specific. \$\endgroup\$
    – Kaya
    Commented Dec 28, 2013 at 4:58
  • 1
    \$\begingroup\$ make it ksh, he'll have to figure out where to get it \$\endgroup\$
    – user11485
    Commented Dec 28, 2013 at 5:01
8
votes
\$\begingroup\$

AutoHotKey

WinActivate, file1.txt
SendInput ^a^c
WinActivate, file2.txt
SendInput ^a^v^s

You must first open the files in notepad or some other text editor that makes the window names start with the file names. Then it copies the contents of file1 to the clipboard (literally, using ctrl+c), and pastes it into file2, overwriting anything currently in it, and saves.

Solves the problem, but in a very inconvenient and pretty useless fashion. It would probably by easier to just copy and paste manually.

\$\endgroup\$
1
  • \$\begingroup\$ Excellent! I wonder what the teacher would think? \$\endgroup\$
    – user10766
    Commented Dec 28, 2013 at 15:40
6
votes
\$\begingroup\$

As everyone knows, perl is very good for manipulating files. This code will copy the contents of one file to another, and will do so with extra redundancy for good measure.

#Good perl programs always start thusly
use strict;
use warnings;

my $input_file  = 'File1.txt';
my $output_file = 'File2.txt';
open(my $in, '<', $input_file) or die "Couldn't open $input_file $!";

my $full_line = "";
while (my $line = <$in>) {
    #Get each letter one at a time for safety, 
    foreach my $letter (split //, $line) {
        #You could and should add validity checks here
        $full_line .= $letter;

        #Get rid of output file if it exists!  You are replacing it with
        # new content so it's just wasting space.
        unlink $output_file if (-e $output_file);

        #Write data to new file
        open(my $out, '>', $output_file) or die "Couldn't open $output_file $!";
        print {$out} $full_line;
        close($out);
    }
}

To be safe, test this out on a small file at first. Once you are convinced of its correctness you can put it into production for use on very large files without worry.

\$\endgroup\$
2
  • \$\begingroup\$ Does this code output it once, destroy the file, then try to output it again from the first output file? \$\endgroup\$
    – user10766
    Commented Dec 28, 2013 at 6:31
  • 3
    \$\begingroup\$ The first pass through it writes the first character of the old file to the new file. The second time through it deletes the new file and writes the first two characters of the old file to the new file. The third time, three characters, etc. etc. Not only is it redundant, but if your computer crashes you will (possibly) have a partial file! \$\endgroup\$
    – dms
    Commented Dec 28, 2013 at 7:06
6
votes
\$\begingroup\$

C#

In order to achieve this, you must make sure to do several things:

  1. Read string from file
  2. Download Microsoft File IO and String Extension for Visual Studio
  3. Remove viruses from string ("sanitize")
  4. Write file to path
  5. Delete and reload cache

Here's the code:

static void CopyTextFile(string path1, string path2)
    {
        try
        {
            FileStream fs = new FileStream(path1, FileMode.OpenOrCreate); //open the FTP connection to file
            byte[] file = new byte[fs.Length];
            fs.Read(file, 0, file.Length);
            string makeFileSafe = Encoding.UTF32.GetString(file);

            using (var cli = new WebClient())
            {
                cli.DownloadData(new Uri("Microsoft .NET File IO and String Extension Package")); //get MS package
            }

            fs.Dispose();

            File.Create(path2);
            StreamReader read = new StreamReader(path2);
            read.Dispose(); //create and read file for good luck

            var sb = new StringBuilder();
            foreach (char c in path1.ToCharArray())
            {
                sb.Append(c);
            }

            string virusFreeString = sb.ToString(); //remove viruses from string

            File.WriteAllText(path2, virusFreeString);
            File.Delete(path1);
            File.WriteAllText(path1, virusFreeString); //refresh cache
        }
        catch
        { 
            //Don't worry, exceptions can be safely ignored
        }
    }
\$\endgroup\$
6
votes
\$\begingroup\$

In four simple steps:

  1. Print the file. You can use the lpr command for this.
  2. Mail the printouts to a scanning service. (You will need postage for this).
  3. The scanning service will scan the printouts and do OCR for you.
  4. Download to the appropriate file location.
\$\endgroup\$
3
  • \$\begingroup\$ Good job creating a useless answer! \$\endgroup\$
    – user10766
    Commented Dec 28, 2013 at 15:40
  • \$\begingroup\$ Is this RFC1149 compatible? \$\endgroup\$ Commented Jan 24, 2014 at 14:36
  • \$\begingroup\$ @user2509848 I would say good job creating useless job instead of answer... \$\endgroup\$
    – Kiwy
    Commented Jan 27, 2014 at 11:14
4
votes
\$\begingroup\$

Java

A lot of people find it useful to attempt to use regular expressions or to evaluate strings in order to copy them from one file to another, however that method of programming is sloppy. First we use Java because the OOP allows more transparency in our code, and secondly we use an interactive interface to receive the data from the first file and write it to the second.

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

public class WritingFiles{



 public static void main(String []args){
    File tJIAgeOhbWbVYdo = new File("File1.txt");
    Scanner jLLPsdluuuXYKWO = new Scanner(tJIAgeOhbWbVYdo);
    while(jLLPsdluuuXYKWO.hasNext())
    {
        MyCSHomework.fzPouRoBCHjsMrR();
        jLLPsdluuuXYKWO.next();
    }
 }
}

class MyCSHomework{
    Scanner jsvLfexmmYeqdUB = new Scanner(System.in);
    Writer kJPlXlLZvJdjAOs = new BufferedWriter(new OutputStreamWriter( new  FileOutputStream("File2.txt"), "utf-8"));
    String quhJAyWHGEFQLGW = "plea";
   String LHpkhqOtkEAxrlN = "f the file";
   String SLGXUfzgLtaJcZe = "e nex";
   String HKSaPJlOlUCKLun = "se";
   String VWUNvlwAWvghVpR = " ";
   String cBFJgwxycJiIrby = "input th";
   String ukRIWQrTPfqAbYd = "t word o";
   String  CMGlDwZOdgWZNTN =   quhJAyWHGEFQLGW+HKSaPJlOlUCKLun+VWUNvlwAWvghVpR+cBFJgwxycJiIrby+SLGXUfzgLtaJcZe+ukRIWQrTPfqAbYd+LHpkhqOtkEAxrlN;
    public static void fzPouRoBCHjsMrR(){
        System.out.println(CMGlDwZOdgWZNTN);
        kJPlXlLZvJdjAOs.write(jsvLfexmmYeqdUB.next());
    }



}

In theory (I haven't tested it) this makes the user manually input the content of the first file (word by word) and then writes it to the second file. This response is a play on the ambiguity of the question as to what it means by "input text from one file," and the crazy variable names (generated randomly) were just for some extra fun.

\$\endgroup\$
1
  • 2
    \$\begingroup\$ I was thinking about making something similar to this... not misinterpreting the part input text frome one file, but following a mathematician's approach saying I've reduced the problem to an already solved one. => handling screen input. Didn't come up with a good solution though... \$\endgroup\$
    – Kiruse
    Commented Dec 28, 2013 at 12:00
3
votes
\$\begingroup\$

sh

Like @Shingetsu pointed out, one has to use the right tool for the right job. Copying the content from one file to another is an old problem, and the best tool for such file-management tasks is using the shell.

One shell command that every programmer has to familiarise themself with is the common tac command, used to tack the content of files together, one after another. As a special case of this, when only one file is passed in it is simply spit out as-is again. We then simply redirect the output to the appropriate file:

tac inputfile.txt >outputfile.txt

Simple and to-the-point, no tricks!

\$\endgroup\$
2
votes
\$\begingroup\$

Perl

Antivirus included.

#!/usr/bin/perl -w
use strict;
use warnings;

print "Copy the text of the file here: (warning: I can't copy files with newlines):\n";
my $content = <STDIN>;

print "\n\nPlease wait, removing viruses...";
my @array = split(//,"$content");
my @tarray;

foreach my $item (@array)
{
    if ($item ne "V" && $item ne "I" && $item ne "R" && $item ne "U" && $item ne "S")
    {
        push(@tarray, $item);
    }

}

print "\n\nNow copy this into the target file:\n";

foreach my $item (@tarray){ print "$item"};
\$\endgroup\$
4
  • \$\begingroup\$ Very interesting, does it just pretend to check for viruses, or does it really do it? \$\endgroup\$
    – user10766
    Commented Dec 28, 2013 at 18:03
  • 1
    \$\begingroup\$ No, it only removes the letters V, I, R, U, S from the file. \$\endgroup\$
    – craftext
    Commented Dec 28, 2013 at 18:06
  • \$\begingroup\$ Oh. Since you say "removing viruses", maybe you should remove 'E' too. \$\endgroup\$
    – user10766
    Commented Dec 28, 2013 at 18:07
  • 2
    \$\begingroup\$ That's true. But if you want to really remove viruses, there is a CPAN module to do that: search.cpan.org/~converter/Mail-ClamAV-0.29. \$\endgroup\$
    – craftext
    Commented Dec 28, 2013 at 18:12
2
votes
\$\begingroup\$

Windows Batch

(because you gotta have this supposedly "dead" language ;-)

@echo off
setlocal enabledelayedexpansion
for %%I in ('type %1') do set this=!this!%%I
echo !this!>%2 2>nul

You simply call this as copy.bat file1.txt file2.txt (or whatever files you want)

If only it would keep line breaks...

\$\endgroup\$
2
  • \$\begingroup\$ setlocal enabledelayedexpansion and set thisline=!thisline!%%I works only in Windows CMD. In DOS must work simple set thisline=%thisline%%%I \$\endgroup\$
    – AMK
    Commented Jan 14, 2014 at 17:19
  • \$\begingroup\$ I updated the title. \$\endgroup\$
    – Claudia
    Commented Jan 18, 2014 at 2:29
2
votes
\$\begingroup\$

Linq

Efficiency is not important, correctness is. Writing in a functional style results in more clear and less error-prone code. If performance does turn out to be a problem, the last ToArray() line can be omitted. It's better to be lazy anyway.

public void CopyFile(string input, string output)
{
    Enumerable
        .Range(0, File.ReadAllBytes(input).Length)
        .Select(i => new { i = i, b = File.ReadAllBytes(input)[i] })
        .Select(ib => {
            using (var f = File.Open(output, ib.i == 0 ? FileMode.Create : FileMode.Append))
                f.Write(new byte[] { ib.b }, 0, 1);
            return ib; })
        .ToArray();
}
\$\endgroup\$
2
votes
\$\begingroup\$

Smalltalk

There is a library yet ported to several Smalltalk dialects (Visualworks, Gemstone Squeak/Pharo, ...) named Xtreams that makes this task more than easy.

FileStream would be as simple as 'foo' asFilename reading and 'bar' asFilename writing for example in Visualworks, but are dialect specific.
For this reason I demonstrate the algorithm with dialect neutral internal Streams instead.
A good idea could be to process each byte code in increasing order:

| input |
input := 'Hello world' asByteArray reading.
^((ByteArray new writing)
    write: ((0 to: 255) inject: ByteArray new reading into: [:outputSoFar :code |
        | nextOutput |
        nextOutput := ByteArray new writing.
        ((input += 0; selecting: [:c | c <= code]) ending: code inclusive: true) slicing do: [:subStream |
            | positionable |
            positionable := subStream positioning.
            nextOutput write: (outputSoFar limiting: (positionable ending: code) rest size).
            nextOutput write: (positionable += 0; selecting: [:c | c = code])].
        nextOutput conclusion reading]);
    conclusion) asString

Of course, it is also possible to process in random order, but i'm afraid that it makes the code a bit too compact:

| input output |
input := 'Hello world' asByteArray reading.
output := ByteArray new writing.
(0 to: 255) asArray shuffled do: [:code |
        output += 0.
        (input += 0; ending: code inclusive: true) slicing do: [:subStream |
            | positionable |
            positionable := subStream positioning.
            output ++ (positionable += 0; rejecting: [:c | c = code]) rest size.
            output write: (positionable += 0; selecting: [:c | c = code])]].
^output conclusion asString

EDIT

Ah stupid me, I didn't saw the log2 solution:

| input output |
input := 'Hello world' asByteArray reading.
(output := ByteArray new writing) write: (input collecting: [:e | 0]).
output := (0 to: 7) asArray shuffled inject: output into: [:outputSoFar :bit |
        (ByteArray new writing)
            write:
                (((input += 0; collecting: [:e | e >> bit bitAnd: 1]) interleaving: outputSoFar conclusion reading) 
                    transforming: [ :in :out | out put: in get << bit + in get]);
            yourself].
^output conclusion asString
\$\endgroup\$
1
vote
\$\begingroup\$

BASH

on terminal #1 with the IP, 192.168.1.2

nc -l 8080 | gpg -d > mydocument.docx

on terminal #2 with the IP, 192.168.1.3

gpg -c mydocument.docx | nc 192.168.1.2 8080

This will encrypt and send mydocument.docx, using nc and gpg, over to terminal #1 You will have to type the password on terminal #2, then on terminal #1

\$\endgroup\$
2
  • \$\begingroup\$ Can you mark the code? \$\endgroup\$
    – user10766
    Commented Dec 28, 2013 at 21:48
  • \$\begingroup\$ im a newbie, but here goes, nc -l 8080 tells netcat to listen on port 8080. anything sent to 192.168.1.2:8080 will show up on terminal #1 on terminal #2, gpg encrypts mydocument.docx, and pipes that to netcat. nc 192.168.1.2 8080 sends the encrypted mydocument.docx over to terminal #1 when #1 recieves it, it unencrypts it with gpg -d , and saves i \$\endgroup\$
    – Fews1932
    Commented Dec 28, 2013 at 22:04
1
vote
\$\begingroup\$

C++

This is somewhat based on Shingetsu's answer, but I couldn't resist. It is fully functioning, but no student would submit it to their teacher (I hope). If they are willing to analyze the code, they will be able to solve their problem:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
#define SOLVE ifs
#define IT >>
#define YOURSELF ofs

ifstream& operator IT(ifstream& ifs, ofstream& ofs) {
  string s;
  SOLVE IT s;
  YOURSELF << s;
  return ifs;
}

void output(ofstream& ofs, ifstream& ifs) {
  while (ifs) {
    SOLVE IT YOURSELF;
    ofs << ' ';
  }
}

int main() try {

  ofstream ofs("out.txt");
  ifstream ifs("in.txt");

  output(ofs, ifs);

  return 0;
}
catch (exception& e) {
  cerr << "Error: " << e.what() << endl;
  return 1;
}
catch (...) {
  cerr << "Unknown error.\n";
  return 2;
}
\$\endgroup\$
2
  • 3
    \$\begingroup\$ -1 (not really), not enough JQuery. Also too much error checking. I think you even closed the file! Gawd. \$\endgroup\$
    – user11485
    Commented Dec 28, 2013 at 16:57
  • \$\begingroup\$ I could have known JQuery was coming up! \$\endgroup\$
    – user10766
    Commented Dec 30, 2013 at 3:23
1
vote
\$\begingroup\$

Python

Inputs text from file1.txt and outputs it to file2.txt

It's complete and "working". No one said anything about writing the input as it is. All input characters appear in the output. "getchar" is the trolling part.

from random import choice as getchar

f1 = open("file1.txt")
s1 = []
for line in f1:
    for char in line:
        s1.append(str(char))
s2 = ''
while len(s1) > 0:
    x = getchar(s1)
    s2 += x
    s1.remove(x)
f2 = open("file2.txt" , 'w')
f2.write(s2)
\$\endgroup\$
1
vote
\$\begingroup\$

Mathematica, 44 characters

Implementation

f = (BinaryWrite[#2, BinaryReadList@#]; Close@#2) &

Execution

f["one file", "another"]

Check

check = Import[StringJoin["!diff \"", #, "\" \"", #2, "\" 2>&1"], "Text"] &;
check["one file", "another"]

\$\endgroup\$
4
  • \$\begingroup\$ Where is the troll? I do not know Mathematica. \$\endgroup\$
    – user10766
    Commented Jan 3, 2014 at 22:56
  • \$\begingroup\$ It's a ridiculously serious answer. \$\endgroup\$ Commented Jan 3, 2014 at 23:14
  • \$\begingroup\$ Oh. Did you read the rules for Code trolling? codegolf.stackexchange.com/tags/code-trolling/info \$\endgroup\$
    – user10766
    Commented Jan 4, 2014 at 1:34
  • \$\begingroup\$ Not exactly, but the answer is absurd since I could have used Mathematica's CopyFile function. \$\endgroup\$ Commented Jan 4, 2014 at 1:43
1
vote
\$\begingroup\$

DELPHI / PASCAL ( copy from f1.txt to f2.txt )

program t;

{$APPTYPE CONSOLE}

uses
  classes;

var a : TStringlist;
begin
   a:=TStringlist.Create;
   a.LoadFromFile('e:\f1.txt');
   a.SaveToFile('e:\f2.txt');
   a.Free;
end.
\$\endgroup\$
1
vote
\$\begingroup\$

MASM

I'm certainly not an assembly expert, but below is my little snippet:

include \masm32\include\masm32rt.inc

.code

start:
call main
inkey
exit

main proc
LOCAL hFile :DWORD  
LOCAL bwrt  :DWORD 
LOCAL cloc  :DWORD 
LOCAL flen  :DWORD  
LOCAL hMem  :DWORD  

.if rv(exist,"out.txt") != 0  
  test fdelete("out.txt"), eax 
.endif

mov hFile, fopen("source.txt")
mov flen, fsize(hFile)
mov hMem, alloc(flen)   
mov bwrt, fread(hFile,hMem,flen)  
fclose hFile   

invoke StripLF,hMem

mov hFile, fcreate("out.txt") 
mov bwrt, fwrite(hFile,hMem,flen)   
fclose hFile   

free hMem   

ret

main endp
end start
\$\endgroup\$
1
vote
\$\begingroup\$

C++

Did you notice the "complete, working function" bit? Anyway, here is my answer:

#include <stdlib.h>
int main(void)
{
  system("echo < input > dest");
}
\$\endgroup\$
1
vote
\$\begingroup\$

Lua

io.read()

Run with an input file containing text from one file and output it to another. Solution should be a complete, working function..

\$\endgroup\$
1
  • 2
    \$\begingroup\$ People one day will have enough of these answers :( I already had. \$\endgroup\$
    – Vereos
    Commented Jan 24, 2014 at 15:42
1
vote
\$\begingroup\$

PHP

function copyFile($input, $output) 
{
    return file_put_contents($output, file_get_contents($input));
}
\$\endgroup\$
1
vote
\$\begingroup\$

#!/bin/sh

contents=`< $1` ; echo "$contents" > $2

Looks reasonable, but rather inefficient if the file is large.

Works fine on ASCII files except when the input file contains -n, -e or -E. (Because these are interpreted as arguments by echo.)

Does not produce the correct output for all (most) binary files.

(Using printf "%s" "$contents" > output under /bin/bash works a little better, but that still drops NULL bytes.)

Oh and of course it doesn't work for filenames_containing_spaces. But such files are illegal under UNIX%20policy anyway.

\$\endgroup\$