2009-01-04 100 views
4

有沒有辦法將文本從文件中的某個點寫入文件?將文本寫入文件的中間

例如,我打開一個10行文本的文件,但我想寫一行文本到第5行。

我想一種方法是使用readalllines方法將文件中的文本行作爲數組返回,然後在數組中的某個索引處添加一行。

但是有一個區別在於,某些集合只能將成員添加到最終目標以及某些目標。要仔細檢查,數組總是允許我在任何索引處添加一個值,對吧? (我敢肯定,其中一本書的其他着作也是如此)。

此外,有沒有更好的方法去做這件事?

感謝

+0

重複:http://stackoverflow.com/questions/98484/how-to-insert-characters-to-a-file-using-c – 2009-01-04 03:05:36

回答

3

哦,嘆了口氣。查找「主文件更新」算法。

這裏是僞代碼:

open master file for reading. 
count := 0 
while not EOF do 
    read line from master file into buffer 
    write line to output file  
    count := count + 1 
    if count = 5 then 
     write added line to output file 
    fi 
od 
rename output file to replace input file 
1

如果你正在讀/寫小文件(比如說,在20兆 - 是的,我認爲20M「小」),而不是寫他們經常(如,沒有幾次秒)然後只是讀/寫整個事情。

像文本文檔這樣的串行文件不是爲隨機訪問而設計的。這就是數據庫的用途。

1

使用系統;

using System.Collections.Generic;

using System.Linq;

using System.Text;

public class Class1 
{      
    static void Main() 
    { 
     var beatles = new LinkedList<string>(); 

     beatles.AddFirst("John");       
     LinkedListNode<string> nextBeatles = beatles.AddAfter(beatles.First, "Paul"); 
     nextBeatles = beatles.AddAfter(nextBeatles, "George"); 
     nextBeatles = beatles.AddAfter(nextBeatles, "Ringo"); 

     // change the 1 to your 5th line 
     LinkedListNode<string> paulsNode = beatles.NodeAt(1); 
     LinkedListNode<string> recentHindrance = beatles.AddBefore(paulsNode, "Yoko"); 
     recentHindrance = beatles.AddBefore(recentHindrance, "Aunt Mimi"); 
     beatles.AddBefore(recentHindrance, "Father Jim"); 


     Console.WriteLine("{0}", string.Join("\n", beatles.ToArray())); 

     Console.ReadLine();      
    } 
} 

public static class Helper 
{ 
    public static LinkedListNode<T> NodeAt<T>(this LinkedList<T> l, int index) 
    { 
     LinkedListNode<T> x = l.First; 

     while ((index--) > 0) x = x.Next; 

     return x; 
    } 
}