我正在嘗試將一個非常大的字符數組的內容寫入硬盤。 我有以下數組(實際上它的大小將會非常大) 我使用數組作爲位數組,並且在向其中插入指定數量的位後,我必須將其內容複製到另一個數組並寫入這個複製到硬盤上。然後,通過將其分配給0以備將來使用,清空數組的內容。如何將數組的內容寫入硬盤
unsigned char bit_table_[ROWS][COLUMNS];
我正在嘗試將一個非常大的字符數組的內容寫入硬盤。 我有以下數組(實際上它的大小將會非常大) 我使用數組作爲位數組,並且在向其中插入指定數量的位後,我必須將其內容複製到另一個數組並寫入這個複製到硬盤上。然後,通過將其分配給0以備將來使用,清空數組的內容。如何將數組的內容寫入硬盤
unsigned char bit_table_[ROWS][COLUMNS];
使用文件或數據庫...
一個文件很容易創建:
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」, – 2014-12-12 21:46:05
使用ofstream
,copy
和ostream_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;
}
你可以存儲陣列的價值在文件
,所以你需要
包括fstream的頭文件和使用std :: ostream;
聲明類型ofstream的
打開文件
檢查打開的文件錯誤
使用文件
關閉該文件的一個變量時訪問不需要更長時間
#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; }
您使用的是C還是C++?解決方案可能會非常不同。 – crashmstr 2011-12-27 14:53:26
@crashmstr:任何事情都可以,但我會很高興與c + + – John 2011-12-27 14:54:24
你需要複製它嗎?爲什麼不直接將現有數組排隊到某個線程或池以寫入磁盤並創建一個新的空的? – 2011-12-27 16:32:27