简体   繁体   English

C:在不搜索的情况下写入文本文件中的特定行

[英]C: Write to a specific line in the text file without searching

Hello I have file with text: 你好我有文本文件:

14 
5 4
45 854
14 
4 
47 5

I need to write a text to a specific line. 我需要将文本写到特定行。 For example to the line number 4 (Doesn't matter whether I will append the text or rewrite the whole line): 例如第4行(我是否要附加文本还是重写整行都没有关系):

14 
5 4
45 854
14 new_text
4 
47 5

I have found function fseek(). 我发现了功能fseek()。 But in the documentation is written 但是在文档中写的


fseek(file pointer,offset, position); fseek(文件指针,偏移量,位置);

"Offset specifies the number of positions (bytes) to be moved from the location specified bt the position." “偏移量指定了要从指定位置移出的位置数(字节)。”


But I do not know the number of bites. 但是我不知道被咬的次数。 I only know the number of lines. 我只知道行数。 How to do that? 怎么做? Thank you 谢谢

You can't do that, (text) files are not line-addressable. 您无法做到这一点,(文本)文件不可行寻址。

Also, you can't insert data in the middle of a file. 另外,您不能在文件中间插入数据。

The best way is to "spool" to a new file, ie read the input line by line, and write that to a new file which is the output. 最好的方法是“假脱机”到新文件,即逐行读取输入,然后将其写入到新文件即输出。 You can then easily keep track of which line you're on, and do whatever you want. 然后,您可以轻松地跟踪您所在的行,并执行所需的任何操作。

I will assume that you are going to be doing this many times for a single file, as such you would be better indexing the position of each newline char, for example you could use a function like this: 我将假设您将对单个文件执行多次操作,这样您最好为每个换行符的位置编制索引,例如可以使用如下函数:

long *LinePosFind(int FileDes)
{
    long * LinePosArr = malloc(500 * sizeof(long));
    char TmpChar;
    long LinesRead = 0;
    long CharsRead = 0;
    while(1 == read(FileDes, &TmpChar, 1))
    {
        if (!(LinesRead % 500)
        {
            LinePosArr = realloc(LinePosArr, (LinesRead + 500) * sizeof(long));
        }
        if (TmpChar == '\n')
        {
            LinePosArr[LinesRead++] = CharsRead;
        }
        CharsRead++;
    }
    return LinePosArr;
}

Then you can save the index of all the newlines for repeated use. 然后,您可以保存所有换行符的索引以供重复使用。

After this you can use it like so: 之后,您可以像这样使用它:

long *LineIndex = LinePosFind(FileDes);
long FourthLine = LineIndex[3];

Note I have not checked this code, just written from my head so it may need fixes, also, you should add some error checking for the malloc and read and realloc if you are using the code in production. 注意:我没有检查过这段代码,只是从头开始编写,因此可能需要修复。此外,如果在生产环境中使用该代码,则应添加一些错误检查malloc并读取和重新分配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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