簡體   English   中英

刪除文本文件C ++的一部分

[英]Remove parts of text file C++

我有一個名為copynumbers.txt的文本文件,在使用示例時,我需要刪除一個數字后的一些數字,該文本文件將包含以下內容

   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15

每個整數應占用4個字節的空間。

我想刪除或刪除數字7到15,同時保留1到6,然后將數字30添加到它。

因此,文件將保留1到6並擺脫7到15,然后在那之后我要保留30。

我的新文件應如下所示

1 2 3 4 5 6 30

我的問題是如何在不覆蓋數字1到6的情況下做到這一點? 因為當我使用

std::ofstream outfile;
outfile.open ("copynumbers.txt");

它將覆蓋所有內容,並在文件中僅保留30

當我使用

ofstream outfile("copynumbers.txt", ios::app);

它將在15之后追加30,但不會刪除任何內容。

我的一些代碼:

#include <iostream>
#include <fstream>
using namespace std;
int main() {
    ofstream outfile("copynumbers.txt", ios::app);

    outfile.seekp(0, outfile.end);

    int position = outfile.tellp();

    cout << position;

    //outfile.seekp(position - 35);

    outfile.seekp(28);
    outfile.write("  30",4);

    outfile.close();    

    return 0;
}

嘗試“就地”修改文件通常是一個壞主意-如果出現任何問題,則最終會導致文件損壞或丟失。 通常,您將執行以下操作:

  • 打開原始文件進行輸入
  • 創建用於輸出的臨時文件
  • 讀取輸入文件,處理,寫入臨時文件
  • 如果成功,則:
    • 刪除原始文件
    • 重命名臨時文件為原始文件名

這不僅是一種安全的策略,還使修改內容的過程變得更加容易,例如,從文件中“刪除”某些內容,而在讀取輸入時,只需跳過該部分即可(即,不要將該部分寫入輸出文件中) )。

您必須使用seekp函數。 看一下這個。

http://www.cplusplus.com/reference/ostream/ostream/seekp/

我建議讀取內存中的原始文件,對內存進行必要的更改,然后從頭開始將所有內容寫到文件中。

std::istream_iterator幫助您嗎? 如果您知道只需要前6個字,則可以執行以下操作:

std::istringstream input( "   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15" );
std::vector< int > output( 7, 30 ); // initialize everything to 30

std::copy_n( std::istream_iterator< int >( input ), 6, output.begin() ); // Overwrite the first 6 characters

如果希望將輸出選項卡分開,則可以對輸出執行以下操作:

std::ofstream outfile( "copynumbers.txt" );

outfile << '\t';
std::copy( outfile.begin(), outfile.end(), std::ostream_iterator< int >( outfile, "\t" ) );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM