简体   繁体   中英

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):

14 
5 4
45 854
14 new_text
4 
47 5

I have found function fseek(). But in the documentation is written


fseek(file pointer,offset, position);

"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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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