写入文件中的特定位置,但首先删除旧内容

时间:2013-08-04 02:29:09

标签: c++ file

我想在已存在的文件中写一些具体位置,但我想在写新内容之前删除此位置的旧内容。

例如,假设以下是目标文件的内容。

27013.
Anderson Alston.
22.
9 Hall st.
25/7/2013.
0.      << target position here

现在,修改后的文件内容将是

27013.
Anderson Alston.
22.
9 Hall st.
25/7/2013.
190.    << this position has been modified

最后,以下是我写的代码。

cout << "Amount of deposit: ";
cin >> amount;
ofstream ifile("file.txt", ios::out|ios::trunc);
ifile.seekp(pos); // `pos` is variable that stores the position
ifile << amount << ".";
ifile.close();

4 个答案:

答案 0 :(得分:3)

您不能直接在文件中间插入数据,就像您无法将数据插入数组中间一样。您必须在插入点之后移动所有内容,以便为新数据腾出空间。

一般来说,我认为使用这样的文件是个坏主意。读取文件,执行您需要的任何处理,然后将完整文件写回。此外,您可以避免以这种方式轻易破坏文件。

答案 1 :(得分:2)

您无法以这种方式将数据插入文件中。

文件是一组连续的字节,要将其他数据引入特定区域,您需要为新内容“腾出空间”。这是通过分配更多空间然后移动值来实现的,这样你就可以写到你想要的地方。

我当然不建议转移(读/写)文件本身的字符。将文件的内容读入char缓冲区,可以更容易地操作数据。您可以考虑使用char数组数组,因此每行都有一个char数组。这样,您就可以在每行的基础上操作数据,并在完成所有修改后回写文件。

答案 2 :(得分:0)

好的,希望能给你答案......

首先,您必须知道您在问题中要求的内容只是部分可行。我的意思是,

一个。您可以在不将整个文件读入内存的情况下更改文件记录,但是

湾您无法在不移动其他记录的情况下将新记录插入文件中间。

要执行上述任务'a',您只需使用搜索功能到所需位置,然后更新记录。

要完成任务'b',因为你是初学者,所以最好使用数组。我不会在这里为你编写完整的代码。如果这就是你想要的,你宁愿进入我的课程而不是你的 C课程:)

所以这是一个粗略的算法。

要插入记录:

Input data
Open the file to append. (alternatively you may seek to the end of the file)
Write the record
Close the file.

要ED记录。

Input a record item to search. Eg: ID or name or something unique.
Open the file (for read/write)
RecordNum = 0
found = false
While not eof and not found
  Read record
  If match found
    found= true
    display info so you can see the data
    input new fields (changes)
    seek to postion RecordNum
    Write the record to the position.
  Else
    Increment RecordNum
  End if
End while
if not found show error or something you like.
close file

在上面的方法中,您必须使用键入的文件。这意味着您必须为每条记录定义记录结构(使用struct)。

答案 3 :(得分:-1)

你可以这样打开文件:

fstream ifile("file.txt", ios::in | ios::out);