How can I get 4 bytes per reading in a file

This is a C program:

I have a binary file and I need to read 4 bytes per reading and store it as type long. I tried fgetc, I did 4 fgetc which I stored in an array of type char but I hit a brick wall when I tried to convert the array to type long.

1. Maybe I am overlooking something, can I read a type long directly from a binary file?

2. Or can I convert an array of type char to a long?

Assuming the file is stored in "natural" system endianness, you can just use fread:

1
2
3
long foo;

fread(&foo,1,sizeof(long),yourfile);
I used the fread and it works, then another problem shows up. at the end of file I only read 2 bytes instead of 4, there is no more to read, and my program crashed'. It says stack is corrupted.

How do I get around it, considering I have to the number of bytes that I read happens after the fact. meaning I have to read first to find out that I am short by few bytes.
If yourself created that file, add a 2 byte padding after that. do this in the program that creates the file.
To majidkamali1370: In response to your suggestion:
add a 2 byte padding after that. do this in the program that creates the file

The program is a school homework. and the test file is furnished by my professor. He mentioned to us that our code have to deal with, upon reaching end-of-file and the bytes read is less than 4. And since he mentioned that he intentionally provided a binary file that will test that condition. We are not to modify the TestFile.

I can read the entire file and count the bytes and do a, if ((bytecount % 4) != 0) and when the result is true this tells that at the end I can expect to read less that 4 bytes. I can also do "numberOfRead= bytecount/4; and just do that "numberOfRead" access to the file. However, I can guarantee that this is not the solution he wants to see.

Anyway, I appreciate all the feedback and actually I followed "Disch" suggestion used "fread" instead of sticking with "fscanf" and it worked. I am assuming that the crashing of the program has nothing to do with the "fread" function but a bug in my program.

Keep feeding your brainstorm, The more suggestion I get the better I could deal with my homework.
crashing mean an exception.
add a try...catch block around fread function.
In the catch block add the fread function with a 2 byte short variable and around that fread, add a try...catch block if the content is one-byte wide.
Something like below
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
try
{
   ...
   fread(&foo1,1,sizeof(long),yourfile);
   ...
}
catch(...)
{
   try
   {
      ...
      fread(&foo2,1,sizeof(short),yourfile);
      ...
   }
   catch(...)
   {
      fread(&foo3,1,sizeof(char),yourfile);
   }
}
Topic archived. No new replies allowed.