[英]Writing text to the middle of a file
有沒有辦法可以從文件中的某個點向文件寫入文本?
例如,我打開一個10行文本的文件,但我想寫一行文本到第5行。
我想一種方法是使用readalllines方法將文件中的文本行作為數組返回,然后在數組中的某個索引處添加一行。
但有一個區別是,有些集合只能添加成員到最后,有些集合可以在任何目的地。 要仔細檢查,數組總是允許我在任何索引處添加一個值,對吧? (我確定我的一本書說其他明智的)。
還有,有更好的方法來解決這個問題嗎?
謝謝
哦,嘆了口氣。 查找“主文件更新”算法。
這是偽代碼:
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
如果您正在讀/寫小文件(例如,20兆字節以下 - 是的,我認為20M“小”)並且不經常編寫它們(例如,不是幾秒鍾),那么只需讀/寫整個文件。
像文本文檔這樣的串行文件不是為隨機訪問而設計的。 這就是數據庫的用途。
using System;
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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.