如何在文本文件中间插入字符? [英] How to insert char in middle of text file?

查看:77
本文介绍了如何在文本文件中间插入字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我想在文本文件中插入字符.我想将字符 (DAD1) 打印到文本文件的中间(HERE with DA D1),文本文件看起来像这样 =>

Firstly, I want to insert characters into a text file. I want to print the characters (DAD1) into the middle of the text file (HERE with DA D1) and the text file looks like this =>

@2100
AB CD EF 12 43 56
A3 B2 34 56 .....
...............78
@ffb4
FF FF FF FF(***HERE***)
@ffc0
FA 21 FA 21 ....

我尝试使用 fprintf,但它打印在文件末尾.这是我的编码部分 =>

I tried to use fprintf but it prints at the end of the file. Here is my coding part =>

fp = fopen("testing.txt", "r+");

if (fp)
{
    while (c != EOF)
    {
        c = getc(fp);
        if (c == '@')
        {
            cout << c ;
            while (c != '\n')
            {

                c = getc(fp);
                cout << c ;

            }
            addr ++ ;
        }
        else
        {
            if (addr == 1)
              { ***DO SOMETHING***}

            else if (addr == 2)
             {
              char higha = hia.to_ullong() + ((hia.to_ullong() >= 10) ? 55 : 48);
              char highb = hib.to_ullong() + ((hia.to_ullong() >= 10) ? 55 : 48);
              char lowa  = loa.to_ullong() + ((loa.to_ullong() >= 10) ? 55 : 48);
             char lowb  = lob.to_ullong() + ((lob.to_ullong() >= 10) ? 55 : 48);
             fprintf(fp, "%c", higha);
             fprintf(fp, "%c", highb);
             fprintf(fp, " ");
             fprintf(fp, "%c", lowa);      
             fprintf(fp, "%c", lowb);
             }
         }
    }
}

我尝试使用 SEEK_CUR,但我不明白它是如何工作的.或者有其他方法吗???

I try to use SEEK_CUR but I don't understand how it works. Or have another way to do it???

推荐答案

您不能在现有文件的前面或中间插入/删除数据,只能向/从末尾插入/删除数据.

You cannot insert/remove data to/from the front or middle of an existing file, only to/from the end.

如果您的原始文件小到可以完全放入内存中,您可以将整个文件读入内存,根据需要对其进行操作,然后将其写回到新文件中,覆盖原始文件.

If your original file is small enough to fit entirely in memory, you can read the whole file into memory, manipulate it as needed, and then write it back out to a new file, overwriting the original.

否则,您将需要从原始文件读取并将其数据写入辅助文件,直到到达要插入/删除数据的位置,然后将所需数据写入/从新文件中写入/从新文件中删除需要,然后完成读取原始文件并将其写入新文件.然后用新文件替换原来的文件.

Otherwise, you will need to read from the original file and write its data to a secondary file until you reach the position where you want to insert/remove data, then write/omit the desired data to/from the new file as needed, and then finish reading the original file and writing it to the new file. Then replace the original file with the new file.

这篇关于如何在文本文件中间插入字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆