簡體   English   中英

在c ++中以字節為單位讀取和寫入文件

[英]read and write file in chunks of bytes in c++

我到處都在搜索它,但似乎無法理解如何使用ios :: cur。 我需要以10個字節的塊讀取整個文件,將這些字節寫入緩沖區,然后將該緩沖區寫入另一個文件。 為此,我發送前10個字節,然后發送下10個字節,依此類推。 但是,如何確保指針從上次迭代的位置開始?

char* data = 0;
int i = 0;
std::ifstream is("test.txt", std::ifstream::binary);

if (is)
{
    is.seekg(0, is.end);
    int size = is.tellg();

    cout << size << endl;

    ofstream obj;
    obj.open("new.txt");

    while (!is.eof())
    {
        for (; i <= size;)
        {
            is.seekg(i, is.beg);
            int sz = is.tellg();
            // cout<<sz<<endl;

            data = new char[sz + 1]; //  for the '\0'
            is.read(data, sz);

            data[sz] = '\0'; // set '\0' 
            cout << " data size: " << strlen(data) << "\n";
            cout << data;
            i = i + 10;
        }
        obj.close();
    }
}

您無需重新定位文件位置。

每次讀取操作后,文件位置都會更新。

您應該使用兩個文件對象,一個用於輸入,另一個用於輸出。

在這兩種情況下,文件位置在每次讀寫操作后都會更新。

編輯1:簡化示例

#define BUFFER_SIZE 16
unsigned char buffer[BUFFER_SIZE];
//...
while (input_file.read((char *)buffer, BUFFER_SIZE))
{
  output_file.write((char *)buffer, BUFFER_SIZE);
}

如果input_file的位置為偏移量0,則在第一次讀取后,文件位置將為16。這可以通過以下方式驗證:

int read_file_position = input_file.tellg();  
cout << "input file position: " << read_file_position << endl;
while (input_file.read((char *)buffer, BUFFER_SIZE))
{
  read_file_position = input_file.tellg();
  cout << "input file position: " << read_file_position << endl;
  output_file.write((char *)buffer, BUFFER_SIZE);
}

我認為可以簡化為:

char* data = 0;
int i = 0;
int size = 0;
int sz = 10;
std::ifstream is("test.txt", std::ifstream::binary);
std::ofstream obj;
data = new char[sz+1];
int read_sz = 0;

if (is)
{
    obj.open("new.txt");
    read_sz = is.tellg(); //we are at the beginning of the file now
    while (!is.eof())
    {
        int old_read_sz = read_sz; // old position - before next read
        is.read(data, sz);
        read_sz = is.tellg(); // new position, we've read read_sz-old_read_sz bytes
        data[read_sz-old_read_sz] = '\0'; // set '\0'
        // I hope you wanted the two lines below only for debugging purposes :)
        cout << " data size so far: " << read_sz << "\n";
        cout << data << endl;
        obj.write(data, read_sz-old_read_sz);
     }
    obj.close();
    is.close();
    cout << "total data size: "<< read_sz << endl;
}

讀取數據塊后,文件游標已經移過該塊,因此您無需自己重新定位(並且從當前位置移至末尾/開始和向后移動可能很耗時-特別是在您輸入文件較大)。

順便說一下,這里是有關該主題的教程: http : //www.cplusplus.com/doc/tutorial/files/

更新:忘記了is.read()!=舊的C風格閱讀:-}

暫無
暫無

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

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