2012-02-05 113 views
0

如何寫入文件的特定位置?我的文件包含以下信息:寫入文件C++

100 msc 

我想更新爲:

100 10 20 34 32 43 44 

所以我想跳過100,並與新的輸入陣列覆蓋msc

回答

2

我知道的最好方法是讀取文件的完整內容,然後使用一些字符串操作來覆蓋所需內容。然後,您可以將修改的信息寫回到同一個文件,並覆蓋其內容。

0

ktodisco的方法運行良好,但另一種選擇是打開具有讀/寫權限的文件,並將文件位置指針移動到緩衝區中的寫入位置,然後只寫入所需內容。 C++可能具有這樣的細節,但只需使用C stdio庫即可完成。事情是這樣的:

#include <stdio.h> 

int main() { 
    FILE* f = fopen("myfile", "r+"); 
    /* skip ahead 4 characters from the beginning of file */ 
    fseek(f, 4, SEEK_SET); 
    /* you could use fwrite, or whater works here... */ 
    fprintf(f, "Writing data here..."); 

    fclose(f); 
    return 0; 
} 

您可以使用這些作爲參考: - fseek - fwrite

希望我幫助!

== ==編輯

在C++中iostream類似乎能夠做到以上所有。請參閱:iostream

+0

如果您想要覆蓋文件中的現有數據,則可以使用此功能。但是,如果要將新數據插入現有文件的中間,則必須使用ktodisco的方法。我無法分辨OP究竟在做什麼,但看起來可能是後者。 – Sean 2012-02-05 01:49:32

+0

@Sean我假設OP只是想覆蓋它(因爲他說:「我想跳過100,並用新的輸入數組覆蓋OVERWRITE」msc「)如果是另一種情況,那麼是的,ktodisco的方法是可能最好。 – Miguel 2012-02-05 01:53:39

+0

是的,但「msc」只有三個字符。如果他寫得比那更多,那麼他會寫下在之後發生的事情。這就是爲什麼它看起來像我想插入,並需要先讀取文件。 – Sean 2012-02-05 01:57:12

1

首先你必須明白,你不能修改那樣的文件。
你可以但比它稍微棘手(因爲你需要有空間)。

所以你需要做的是讀取文件並將其寫入一個新文件,然後重新命名文件到原來的文件。

既然你確切地知道在哪裏閱讀和插入什麼做第一。

void copyFile(std::string const& filename) 
{ 
    std::ifstream input(filename.c_str()); 
    std::ofstream output("/tmp/tmpname"); 


    // Read the 100 from the input stream 
    int x; 
    input >> x; 


    // Write the alternative into the output. 
    output <<"100 10 20 34 32 43 44 "; 

    // Copies everything else from 
    // input to the output. 
    output << input.rdbuf(); 
} 

int main() 
{ 
    copyFile("Plop"); 
    rename("Plop", "/tmp/tmpname"); 
}