[英]How can I create 77 files the content of which is the name of each file?
Let's take an example. 让我们举个例子。 A "file1" -file has a content "file1", its own name. “ file1”文件具有自己的名称“ file1”。 A "file2"-file has a content "file2", again its own name. “ file2”文件具有内容“ file2”,同样是其自己的名称。 The pattern continues until we have covered 77 files. 模式一直持续到我们覆盖了77个文件为止。 What is the easiest way to do the 77 files? 做77个文件的最简单方法是什么?
Since I tend to have hard time in compiling, I sum up some details. 由于我往往很难编译,因此我总结了一些细节。
Intructions how to compile the codes 指示如何编译代码
PERMISSIONS: "chmod 700 filename.some_ending" 权限:“ chmod 700 filename.some_ending”
RUNNING: ". ./filename.some_ending" RUNNING:“。./filename.some_ending”
How to compile? 怎么编译?
#!/bin/bash
for i in {1..77}
do
echo file$i > file$i
done
蟒蛇:
for i in range(1,78): open("file" + str(i), "w").write("file" + str(i))
C++: C ++:
#include <sstream>
#include <fstream>
using namespace std;
int main()
{
for (int i = 1; i <= 77; i++) {
stringstream s;
s << "file" << i;
ofstream out(s.str().c_str());
out << s.str();
out.close();
}
return 0;
}
C: C:
#include <stdio.h>
int main() {
char buffer[8];
FILE* f;
int i;
for(i = 1; i <= 77; i++){
sprintf(buffer, "file%d", i);
if((f = fopen(buffer, "w")) != NULL){
fputs(buffer, f);
fclose(f);
}
}
return 0;
}
Java version, for fun. Java版本,很有趣。
import java.io.*;
public class HA {
public static void main(String[] args) throws Exception {
String file = "file";
for (int i = 1; i <= 77; i++){
PrintStream out = new PrintStream(new File(file + i));
out.print(file + i);
out.close();
}
}
}
Perl: Perl:
#!/usr/bin/env perl
for ( my $i = 1; $i <= 77; ++$i )
{
open( my $fh, '>', 'file' . $i );
print { $fh } ( 'file' . $i );
close( $fh );
}
I added the extension, assuming the file's gonna have it. 我添加了扩展名,并假设该文件将具有该扩展名。
Fortran: Fortran:
character(11) file_name
do i=1,77
write(file_name,"('file',i2.2,'.txt')")i
open(unit=1, file=file_name, status='replace')
write(1,"(a)")file_name
close(unit=1)
enddo
end
Python version for those who prefer readable over terse: 对于那些喜欢简洁而不是简洁的人的Python版本:
filenames = ("file%(num)d" % vars() for num in range(1, 78))
for filename in filenames:
open(filename, 'w').write(filename)
C#, why not: C#,为什么不呢?
using System.IO;
namespace FileCreator
{
class Program
{
static void Main(string[] args)
{
for (int i = 1; i <= 77; i++)
{
TextWriter f = new StreamWriter("file" + i);
f.Write("file" + i);
f.Close();
}
}
}
}
红宝石:
77.times { |i| File.open("file#{i+1}", "w") { |f| f.puts "file#{i+1}" } }
Delphi/Free Pascal 德尔福/帕斯卡
program Create77Files;
{$APPTYPE CONSOLE}
uses
Classes, SysUtils;
var
I: Integer;
S: string;
begin
for I := 1 to 77 do
begin
S:= 'file' + IntToStr(I);
with TStringStream.Create(S) do
begin
SaveToFile(S);
Free;
end;
end;
end.
Groovy:
77.times{n->n++;new File('file'+n).withWriter{it.writeLine('file'+n)}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.