2009-01-04 221 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; 
    } 
}