I am using fread to read in a block of 512 bytes from a binary file. I need to define a variable to store the block in the same way you would type
int number;
to define a place to store an integer
what would you use. I am in c++|||To read 512 bytes, I would use a vector%26lt;uint8_t%26gt;, since this is C++, or just vector%26lt;char%26gt; (or even a string)
#include %26lt;iostream%26gt;
#include %26lt;cstdio%26gt;
#include %26lt;vector%26gt;
int main()
{
聽聽聽聽 FILE* file = std::fopen("test.txt", "r");
聽聽聽聽 // remember to test if it opened correctly before calling fread
聽聽聽聽 std::vector%26lt;char%26gt; data(512);
聽聽聽聽 size_t count = std::fread(%26amp;data[0], sizeof data[0], data.size(), file);
聽聽聽聽 ...
}
although if you are using C++, while are you using C I/O? Open the file as an ifstream, and use the simpler
#include %26lt;iostream%26gt;
#include %26lt;fstream%26gt;
#include %26lt;vector%26gt;
int main()
{
聽聽聽聽 std::ifstream file("test.txt");
聽聽聽聽 std::vector%26lt;char%26gt; data(512);
聽聽聽聽 file.read(%26amp;data[0], data.size());
聽聽聽聽 size_t count = file.gcount();
聽聽聽聽 ...
}|||You need an array. If you already know how much data you will be reading, you can define the array as such
int data[512];
Then that gives you 512 integers, you can access them as data[0] through data[511]...
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment