File input/output: Difference between revisions

Content added Content deleted
(awk)
Line 197: Line 197:


=={{header|C sharp|C #}}==
=={{header|C sharp|C #}}==
<lang csharp>using System;
{{works with|C sharp|C #|1.0+}}
using System.IO;
This version will change line terminators if the input file doesn't use CrLf.


namespace FileIO
using System;
{
using System.IO;
class Program
namespace FileIO
{
{
class Program
static void Main(string[] args)
{
{
static void Main(string[] args)
try
{
{
if (File.Exists("input.txt"))
using (StreamReader reader = new StreamReader("input.txt"))
using (StreamWriter writer = new StreamWriter("output.txt"))
{
{
TextReader tr = File.OpenText("input.txt");
string s = reader.ReadLine();
TextWriter tw = new StreamWriter(File.OpenWrite("output.txt"));
while (s != null)
while (tr.Peek() != -1)
{
{
string line = tr.ReadLine();
writer.WriteLine(s);
s = reader.ReadLine();
tw.WriteLine(line);
}
}
tw.Close();
tr.Close();
}
else
{
Console.WriteLine("Input File Missing.");
}
}
}
catch (Exception exception)
{
Console.WriteLine(exception.Message);
}
}
}
}
}
}
}</lang>


There is an easier way:
There is an easier way in .NET 2.0:


using System;
<lang csharp>using System;
using System.IO;
using System.IO;

namespace FileIO
namespace FileIO
{
class Program
{
{
class Program
static void Main(string[] args)
{
{
static void Main(string[] args)
try
{
{
if (File.Exists("input.txt"))
File.WriteAllText("output.txt", File.ReadAllText("input.txt"));
{
}
catch (Exception exception)
File.WriteAllText("output.txt", File.ReadAllText("input.txt"));
}
{
else
Console.WriteLine(exception.Message);
{
Console.WriteLine("Input File Missing.");
}
}
}
}
}
}
}
}</lang>


=={{header|C++}}==
=={{header|C++}}==