Answers:
使用多种编程语言的全部目的是您需要使用正确的工具来完成这项工作。
在这种情况下,我们想将字节从一个文件复制到另一个文件。
虽然我们可以使用诸如bash或ruby之类的东西,或者落入ASM的力量,但我们需要快速,出色的工具和快速的工具。
显而易见的选择是C。
最简单的方法是这样的:
#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_;
}
这是邪恶的,因为它会读取诸如cygwin之类的垃圾信息,对于初学者来说完全是中文,当他意识到这是在寻求帮助时会吓him他,显然是因为C。
#define VERY filename1
#define NOT filename2
#define _ 1
可以(;_;)
使用for循环,使其看起来像一个笑脸。
#define LOL fclose
众所周知,perl非常适合处理文件。此代码会将一个文件的内容复制到另一个文件,并且这样做会额外冗余,以确保良好的性能。
#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);
}
}
为了安全起见,请首先在一个小文件上进行测试。一旦确定了它的正确性,就可以将其投入生产,以用于大型文件而不必担心。
C#
为了实现这一点,您必须确保做几件事:
这是代码:
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
}
}
只需四个简单步骤:
lpr
为此使用命令。很多人发现尝试使用正则表达式或评估字符串以将它们从一个文件复制到另一个文件很有用,但是这种编程方法很草率。首先,我们使用Java是因为OOP可以提高代码的透明度,其次,我们使用交互式界面从第一个文件接收数据并将其写入第二个文件。
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());
}
}
从理论上讲(我尚未测试过),这使用户可以手动输入第一个文件的内容(逐个单词),然后将其写入第二个文件。这种回答是关于这个问题的歧义,即“从一个文件输入文本”是什么意思,疯狂的变量名(随机生成)只是为了增加一些乐趣。
包含防病毒软件。
#!/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"};
(因为您必须拥有这种所谓的“死”语言;-)
@echo off
setlocal enabledelayedexpansion
for %%I in ('type %1') do set this=!this!%%I
echo !this!>%2 2>nul
您只需将其称为copy.bat file1.txt file2.txt
(或您想要的任何文件)
如果可以保持换行符...
setlocal enabledelayedexpansion
并且set thisline=!thisline!%%I
仅在Windows CMD中有效。在DOS中必须工作简单set thisline=%thisline%%%I
效率并不重要,正确性至关重要。以功能风格进行编写可以使代码更清晰,更少出错。如果确实存在性能问题,则可以省略最后的ToArray()行。无论如何最好还是偷懒。
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();
}
短暂聊天
现在有一个库可以移植到名为Xtreams的几种Smalltalk方言(Visualworks,Gemstone Squeak / Pharo等)中,这使这项任务变得异常简单。
FileStream 'foo' asFilename reading
与'bar' asFilename writing
Visualworks中一样简单,例如,但特定于方言。
因此,我将使用方言中立的内部流来演示该算法。
一个好主意是按升序处理每个字节代码:
| 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
当然,也可以按随机顺序进行处理,但恐怕会使代码过于紧凑:
| 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
编辑
愚蠢的我,我没看到log2解决方案:
| 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
在具有IP 192.168.1.2的终端#1上
nc -l 8080 | gpg -d > mydocument.docx
在具有IP 192.168.1.3的2号终端上
gpg -c mydocument.docx | nc 192.168.1.2 8080
这将加密并发送mydocument.docx
,使用nc
和gpg
,到终端#1你将不得不在终端#2键入密码,然后在终端#1
这多少基于Shingetsu的回答,但我无法抗拒。它可以正常运行,但是没有学生可以将其提交给老师(我希望如此)。如果他们愿意分析代码,他们将能够解决他们的问题:
#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;
}
输入来自file1.txt的文本并将其输出到file2.txt
它是完整且“有效的”。没有人说过直接编写输入内容。所有输入字符都出现在输出中。“ getchar”是拖钓的一部分。
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)
实作
f = (BinaryWrite[#2, BinaryReadList@#]; Close@#2) &
执行
f["one file", "another"]
校验
check = Import[StringJoin["!diff \"", #, "\" \"", #2, "\" 2>&1"], "Text"] &;
check["one file", "another"]
CopyFile
函数。
我当然不是组装专家,但是下面是我的小片段:
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
io.read()
使用包含的输入文件运行text from one file and output it to another. Solution should be a complete, working function.
。
contents=`< $1` ; echo "$contents" > $2
看起来很合理,但是如果文件很大,效率会很低。
工程于ASCII文件罚款时,输入文件包含了除-n
,-e
或-E
。(因为这些被解释为自变量echo
。)
没有为所有(大多数)二进制文件产生正确的输出。
(printf "%s" "$contents" > output
在under下使用/bin/bash
效果更好,但是仍然会丢弃NULL字节。)
哦,当然,它不适用于filenames_ contains_spaces。但是,无论如何,根据UNIX%20policy,此类文件是非法的。