在文件中间覆盖

时间:2010-12-21 07:28:50

标签: php c++ c file file-io

问题是我在文件的中间fseek接下来存在一些长度为m的字节,我希望用长度为n的字节替换。简单的write将保留m-n个字节。如果我不愿意更改的m > nm < n部分字节(n-m)将会被覆盖。

我只想用可变长度字节替换已知的startPos to endPos字节流。什么是最佳解决方案。

- 编辑 - 虽然可以通过备份来完成。有没有直接解决方案? 这太乱了?和糟糕的编码。

o = fopen(original, 'r')
b = fopen(backup, 'w')
while(fpos(o) <= startPos){
    buffer += fgetc(o)
}
fwrite(b, buffer)
fwrite(b, replaceMentBytes)
buffer = ""
fseek(o, endPos)
while(!feof(o)){
    buffer += fgetc(o)
}
fwrite(b, buffer)

// now将备份复制到原始

2 个答案:

答案 0 :(得分:5)

最强大的解决方案是从头开始重写整个文件。大多数操作系统只允许您从文件中覆盖字节,而不是插入或删除它们,因此要实现这一点,您必须复制文件,在复制期间替换目标字节。

答案 1 :(得分:0)

使用fstream库,这里是其他人可能会说的简单实现

/**
 * Overwrite a file while replacing certain positions
 */

#include <iostream>
#include <fstream>

using namespace std;

int readFile(char* filename,int& len,char*& result)
{
    ifstream in(filename); // Open the file
    if(!in.is_open())
        return 1;

    // Get file length
    in.seekg(0,ios::end);
    len = (int)in.tellg();
    in.seekg(0,ios::beg);

    // Initialize result
    result = new char[len+1];

    // Read the file and return its value
    in.read(result,len);

    // Close the file
    in.close();

    return 0;
}

void writeFile(char* filename,char* data,int from,int to,int origdata,int trunc)
{
    ofstream out;
    (trunc == 1) ? out.open(filename,ios::trunc) : out.open(filename,ios::app); // Simple ternary statement to figure out what we need to do

    // Find position if we're not starting from the beginning
    if(trunc == 1)
        out.seekp(from);
     else // Otherwise send us to the beginning
        out.seekp(0,ios::beg);

    if(origdata == 1) // If we need to start in the middle of the data, let's do so
        for(int i=0;i<(to-from);++i)
            data[i] = data[from+i]; // Reverse copy

    out.write(data,(to-from));

    out.close();
}

int main()
{
    char* read;
    int len = 0;
    if(readFile("something.txt",len,read) != 0)
    {
        cout<< "An error occurred!" << endl;
        return 0;
    }

    // Example to make this work
    cout<< "Writing new file...\r\n";
    writeFile("something.txt",read,0,20,1,1); // Initial write
    writeFile("something.txt","\r\nsome other mumbo jumbo",21,45,0,0);
    writeFile("something.txt",read,46,100,1,0); // Replace the rest of the file back

    cout<< "Done!\r\n";
    cin.get(); // Pause
    delete [] read;
    return 0;
}

您可以在readFile函数中执行所有操作,或者只在char数组中执行(在本例中为read)。从那里,您可以存储位置并适当地使用writeFile()函数。

祝你好运!
丹尼斯M。