简体   繁体   English

将文本写入文件的中间

[英]Writing text to the middle of a file

Is there a way I can write text to a file from a certain point in the file? 有没有办法可以从文件中的某个点向文件写入文本?

For example, I open a file of 10 lines of text but I want to write a line of text to the 5th line. 例如,我打开一个10行文本的文件,但我想写一行文本到第5行。

I guess one way is to get the lines of text in the file back as an array using the readalllines method, and then add a line at a certain index in the array. 我想一种方法是使用readalllines方法将文件中的文本行作为数组返回,然后在数组中的某个索引处添加一行。

But there is a distinction in that some collections can only add members to the end and some at any destination. 但有一个区别是,有些集合只能添加成员到最后,有些集合可以在任何目的地。 To double check, an array would always allow me to add a value at any index, right? 要仔细检查,数组总是允许我在任何索引处添加一个值,对吧? (I'm sure one of my books said other wise). (我确定我的一本书说其他明智的)。

Also, is there a better way of going about this? 还有,有更好的方法来解决这个问题吗?

Thanks 谢谢

Oh, sigh. 哦,叹了口气。 Look up the "master file update" algorithm. 查找“主文件更新”算法。

here's pseudocode: 这是伪代码:

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

If you're reading/writing small files (say, under 20 megabytes--yes I consider 20M "small") and not writing them that often (as in, not several times a second) then just read/write the whole thing. 如果您正在读/写小文件(例如,20兆字节以下 - 是的,我认为20M“小”)并且不经常编写它们(例如,不是几秒钟),那么只需读/写整个文件。

Serial files like text documents aren't designed for random access. 像文本文档这样的串行文件不是为随机访问而设计的。 That's what databases are for. 这就是数据库的用途。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM