[英]how to write content of an array to hard disk
i am trying to write content of a very large char array to the hard disk. 我试图将一个非常大的char数组的内容写入硬盘。 I have the following array(actually the size of it is going to be very large) I am using the array as a bit array and after inserting a specified number of bits into it I have to copy its content to another array and write this copy into hard disk. 我有以下数组(实际上它的大小将非常大)我使用数组作为位数组,并在插入指定数量的位后,我必须将其内容复制到另一个数组并写入此副本进入硬盘。 I then empty the content of the array by assigning it 0 for further use. 然后我将数组的内容分配为0以供进一步使用。
unsigned char bit_table_[ROWS][COLUMNS];
Use ofstream
, copy
and ostream_iterator
to leverage the power of STL: 使用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;
}
You should open a file for writing, and then write the array to it: 您应该打开一个文件进行写入,然后将数组写入其中:
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
}
References: fopen
, fwrite
, fclose
参考文献: fopen
, fwrite
, fclose
Use a file or a database... 使用文件或数据库......
a file is simple to create : 一个文件很容易创建:
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]);
}
}
to read the contents of the file, you can use fscanf
starting from the beginning of the file : 要读取文件的内容,可以从文件开头使用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]));
}
}
whereas you have to install a database (and number of tables needed) and use specific instructions to write to it. 而你必须安装一个数据库(和所需的表数)并使用特定的指令写入它。
You can Store the value of array in file 您可以将数组的值存储在文件中
so you need 所以你需要
include the fstream header file and using std::ostream; 包含fstream头文件并使用std :: ostream;
declare a variable of type ofstream 声明一个类型为ofstream的变量
open the file 打开文件
check for an open file error 检查打开文件错误
use the file 使用该文件
close the file when access is no longer needed 不再需要访问时关闭文件
#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; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.