【问题标题】:how to write content of an array to hard disk如何将数组的内容写入硬盘
【发布时间】:2012-01-28 13:51:16
【问题描述】:

我正在尝试将一个非常大的字符数组的内容写入硬盘。 我有以下数组(实际上它的大小会非常大) 我将该数组用作位数组,在向其中插入指定数量的位后,我必须将其内容复制到另一个数组并将该副本写入硬盘。然后我通过将其分配为 0 来清空数组的内容以供进一步使用。

unsigned char       bit_table_[ROWS][COLUMNS];

【问题讨论】:

  • 您使用的是 C 还是 C++?解决方案可能非常不同。
  • @crashmstr: 任何都可以,但我会对 c++ 感到满意
  • 一定要复制吗?为什么不将现有数组排队到某个线程或池以写入磁盘并创建一个新的空数组?

标签: c++ c arrays io


【解决方案1】:

您应该打开一个文件进行写入,然后将数组写入其中:

FILE * f;
f = fopen(filepath, "wb"); // wb -write binary
if (f != NULL) 
{
    fwrite(my_arr, sizeof(my_arr), 1, f);
    fclose(f);
}
else
{
    //failed to create the file
}

参考:fopenfwritefclose

【讨论】:

    【解决方案2】:

    使用文件或数据库...

    一个文件很容易创建:

    FILE * f;
    int i,j;
    f = fopen("bit_Table_File", "w");
    for (i = 0 , i< ROWS , i++)
    {
        for (j = 0 , j < COLUMNS , j++)
        {
            fprintf(f, "%2x", bit_table_[i][j]);
        }
    }
    

    要读取文件的内容,可以使用fscanf从文件开头开始:

    FILE* f = fopen("myFile","r");
    for (i = 0 , i< ROWS , i++)
        {
            for (j = 0 , j < COLUMNS , j++)
            {
                fscanf(f, "%2x", &(bit_table_[i][j]));
            }
        }
    

    而您必须安装一个数据库(以及所需的表数量)并使用特定的指令来写入它。

    【讨论】:

    • 我喜欢这个,因为文件是可读的。您需要关闭文件,我会在“%2x”之类的规范中添加一个分隔符,也许是一个逗号
    【解决方案3】:

    使用ofstreamcopyostream_iterator 来利用STL 的强大功能:

    #include <algorithm>
    #include <fstream>
    #include <iterator>
    #include <iostream>
    #include <vector>
    
    using namespace std;
    
    int main() {
        unsigned char bit_table_[20][40];
        for (int i = 0 ; i != 20 ; i++)
            for (int j = 0 ; j != 40 ; j++)
                bit_table_[i][j] = i^j;
        ofstream f("c:/temp/bit_table.bin", ios::binary | ios::out);
        unsigned char *buf = &bit_table_[0][0];
        copy(buf, buf+sizeof(bit_table_), ostream_iterator<unsigned char>(f, ""));
        return 0;
    }
    

    【讨论】:

      【解决方案4】:

      您可以将数组的值存储在文件中

      所以你需要

      • 包含 fstream 头文件并使用 std::ostream;

      • 声明一个流类型的变量

      • 打开文件

      • 检查打开文件错误

      • 使用文件

      • 不再需要访问时关闭文件

        #include <fstream>
        using std::ofstream;
        #include <cstdlib> 
        int main()
        {
           ofstream outdata; 
           int i; // loop index
           int array[5] = {4, 3, 6, 7, 12};
          outdata.open("example.dat"); // opens the file
           if( !outdata ) { // file couldn't be opened
              cerr << "Error: file could not be opened" << endl;
              exit(1);
           }
          for (i=0; i<5; ++i)
              outdata << array[i] << endl;
           outdata.close();
        
           return 0;
        }
        

      【讨论】:

        猜你喜欢
        • 2013-12-29
        • 1970-01-01
        • 2014-04-07
        • 2012-11-28
        • 2014-12-21
        • 2014-08-03
        • 2011-03-20
        • 2012-10-12
        • 2014-02-17
        相关资源
        最近更新 更多