Reputation: 483
int fread(char cc[],int a[],int q)
{
ifstream infile;
infile.open("C:\\Dev-Cpp\\DCS\\Decom\\a.txt",ios::binary);
infile.read(cc,257);
infile.close();
for(int i=0;i<256;i++){a[i]=(unsigned char)cc[i];}
return 0;
}
Now q gets the value from the thread counter, here is what i want to do,
if q is 0, it reads the first 256 characters and if q is 1, it reads the characters from position 256 to 512 and so on
Is this a correct way to do it, cc and a have an array of size 256, or is there a more efficient way of doing this ?
int fread(char cc[],int a[],int q)
{
int ka=0,kb=0;
kb=q*256;
ka=ka+256;
ifstream infile;
infile.open("C:\\Dev-Cpp\\DCS\\Decom\\a.txt",ios::binary);
infile.seekg(256);
infile.read(cc,ka);
infile.close();
for(int i=0;i<256;i++){a[i]=(unsigned char)cc[i];}
return 0;
}
I'm getting a Unhandled exception at 0xb9fb2475 in s949.exe: 0xC0000005: Access violation reading location 0xb9fb2475 when i debug it in vc++ 2010.
Upvotes: 0
Views: 257
Reputation: 57749
Your second version of fread
is close.
Here are some issues I identified.
1. The title is fread
. This is a common C and C++ library function. Could present problems down the road, when fread
is called (which version would they be using?).
2. When passing arrays, the capacity of the array should be passed also.
3. When passing arrays as source, declare them as const
.
4. When passing arrays as the target / destination, pass by reference.
5. Don't use arrays, std::vector
is a lot safer.
6. When position the input file, use your value not a constant 256.
7. Include the size of the record when determining positions. If you are reading integers, multiply by sizeof(int)
.
8. Why read into a local buffer then copy to the client's buffer when you can directly read into the client's buffer?
9. Prefer library routines, such as std::copy, when copying the data.
Upvotes: 1