using System; using System.IO; namespace FileDemo { /* * 示範文字檔案之讀寫 * skj 4/20/2997 * * 假設欲讀入之資料檔格式如下: * 第一列為一個整數代表以下每列有多少個整數數據 * * 欲寫出之資料檔格式與欲讀入之資料檔格式相同 * * 測試: * 欲讀入之資料檔檔名為 Test.dat * 欲寫出之資料檔檔名為 Test.output * * 欲讀入之資料檔內容為(數據之間以一個空白隔開) * 3 * 1 4 2 * 2 3 5 * 7 6 9 * 8 3 12 * 11 10 235 * * 寫出之資料檔內容相同, 但數據之間以TAB('\t')分開, 即 * 3 * 1 4 2 * 2 3 5 * 7 6 9 * 8 3 12 * 11 10 235 * * 注意如果執行偵錯版本, 所用資料檔要放在專案的bin\Debug檔案夾, * 如果不偵錯, 須放在bin\Release檔案夾, 否則檔案名要用完整檔案路徑 */ class Program { static void Main(string[] args) { Console.Write("輸入欲讀入之資料檔名: "); string fileName = Console.ReadLine(); StreamReader input = new StreamReader(fileName); Console.Write("輸入欲寫出之資料檔名: "); fileName = Console.ReadLine(); StreamWriter output = new StreamWriter(fileName); string line; string[] head = new string[2]; // 讀入並寫出第一列 line = input.ReadLine(); int nDataPerLine = int.Parse(line); output.WriteLine(nDataPerLine); // 讀入並寫出後續數據 string[] dataString = new string[nDataPerLine]; int data; while (!input.EndOfStream) { line = input.ReadLine(); dataString = line.Split(' '); for (int i = 0; i < nDataPerLine; ++i) { data = int.Parse(dataString[i]); Console.Write(data + "\t"); output.Write(data + "\t"); } Console.WriteLine(); output.WriteLine(); } output.Close(); input.Close(); Console.ReadLine(); } } }