How to read a binary file using C++11 functions?

Click For Summary

Discussion Overview

The discussion revolves around reading binary files using C++11 functions, with participants comparing C and C++ approaches. The focus includes issues related to file opening modes, data types, and the correct usage of file reading functions.

Discussion Character

  • Technical explanation
  • Debate/contested
  • Mathematical reasoning

Main Points Raised

  • One participant shares a C code snippet for reading binary files and expresses confusion about the C++ version where the head variable is defined as a char array instead of uint32_t.
  • Another participant suggests that the file should be opened with the "rb" mode in the C code and questions the need to open the file after creating an instance of the input stream in C++.
  • A participant points out that the C++ code may not have the mode flags set correctly and mentions the importance of checking if the file can be opened.
  • Concerns are raised about the use of fread with std::ifstream, as fread requires a FILE* pointer, which is not compatible with std::ifstream.
  • One participant mentions a practice of storing the number of elements in the first bytes of a binary file to facilitate reading subsequent data.
  • A participant acknowledges a mistake in their C++ sample code and emphasizes the importance of posting minimal complete code to reproduce issues.
  • Another participant defends the use of C functions in C++ for file operations, stating that they are still widely used.

Areas of Agreement / Disagreement

Participants express various viewpoints on the best practices for reading binary files in C++ and whether to use C functions or C++ streams. There is no consensus on a single correct approach, and multiple competing views remain.

Contextual Notes

Some participants note issues related to file opening modes, the correct data types for reading, and the potential for errors in untested code examples. There are also mentions of the need to ensure the file is in the correct directory.

ORF
Messages
169
Reaction score
19
Hello

I'm using the C functions for reading binary files:
Code:
#include <iostream>
#include <stdio.h>
void main(){
    /*********/
    uint32_t head=0;
    FILE *fin = NULL;
    fin = fopen("myFile.bin","r");
    while(myCondition){
        fread(&head,4,1,fin);
        std::count << std::hex << head << std::endl;
    }
    fclose(fin);
    /*********/
}

But the rest of the program is in C++. I've tried with

Code:
#include <fstream>
#include <ios>
void main(){
    /*********/
    char head[4];
    std::ifstream fin("myFile",std::ios::binary);
    fin.read((char*) &head,sizeof(head));
    while(myCondition){
        fread(&head,4,1,fin);
        std::count << std::hex << head << std::endl;
    }
    fin.close();
/*********/
}

but head doesn't change (I don't know if fread or [count+hex] fails). Is something missing in the C++ code for reading binary files?

Thank you in advance ;)

Greetings
 
Last edited by a moderator:
Technology news on Phys.org
ORF said:
Hello

I'm using the C functions for reading binary files:

#include <iostream>
#include <stdio.h>
void main(){
/*********/
uint32_t head=0;
FILE *fin = NULL;
fin = fopen("myFile.bin","r");
while(myCondition){
fread(&head,4,1,fin);
std::count << std::hex << head << std::endl;
}​
fclose(fin);
/*********/​
}
To open a binary file, use "rb" in the fopen() call.
Also, when you post code, put it inside code tags, like so:
C:
   yada yada yada;
ORF said:
But the rest of the program is in C++. I've tried with
I'm a bit rusty on the C++ file I/O. I'm wondering if you need to open the file after creating an instance of your input stream.
ORF said:
#include <fstream>
#include <ios>
void main(){
/*********/
char head[4];
std::ifstream fin("myFile",std::ios::binary);
fin.read((char*) &head,sizeof(head));
while(myCondition){
fread(&head,4,1,fin);
std::count << std::hex << head << std::endl;
}​
fin.close();
/*********/​
}

but head doesn't change (I don't know if fread or [count+hex] fails). Is something missing in the C++ code for reading binary files?

Thank you in advance ;)

Greetings
 
Regarding the C++ version, here's a link to some docs on the ifstream ctor: http://www.cplusplus.com/reference/fstream/ifstream/ifstream/
You might not have the mode flags set correctly -- you don't include the in flag.

From the page in the link:
If the file cannot be opened, the stream's failbit flag is set.
One possibility is that your code can't find the file "myFile" possibly because it's not in the default directory.
 
Why did you change from uint32_t head to char head[4]? Also, I am surprised that your C++ example compiles, as fread wants a FILE* as its last parameter, not a std::ifstream.
 
I usually store the number of elements in the first 8 bytes, so that you know how many to read next.
C:
std::ifstream inFile( filePath );

uint64_t num;
inFile.read((char*)(&num), sizeof(uint64_t));

std::vector< double > data( num );
inFile.read((char*)data.data(), num*sizeof( double ) );

inFile.close();
 
Hello

Thank you for your replies!

@Jarvis323: your code works fine! In my case, in the binary file there are only integers uint32_t.

@Integrand: that was a mistake in the C++ sample code, sorry; at that point, I should put the "read" fuction (I can't edit).

@Mark44: the file is in the directory; the examples of cplusplus.com (about reading and writing binary files) compiled and worked without problems, but it doesn't work with my binaryFile.bin (I don't know how it's built that binaryfile, just that it's a sequence of uint32_t). I know that the binaryFile is fine because I can read it with the C code.

Thank you for your time! :)

Greetings!
 
ORF said:
@Integrand: that was a mistake in the C++ sample code, sorry; at that point, I should put the "read" fuction (I can't edit).

In my opinion, it is best to post minimal complete code that reproduces the problem. Untested examples can contain additional irrelevant errors.
 
  • Like
Likes   Reactions: Silicon Waffle
@Integrand: thank you for the remark, you're right; I will be more careful next time ;)

Greetings
 
I usually have two different file loaders, one streaming and one big bulk grabber. Just because something is old C functions doesn't make it wrong for C++. fopen/fseek/fread/fclose are still widely used.
 
  • Like
Likes   Reactions: ORF

Similar threads

  • · Replies 6 ·
Replies
6
Views
12K
Replies
6
Views
2K
  • · Replies 5 ·
Replies
5
Views
3K
  • · Replies 75 ·
3
Replies
75
Views
7K
  • · Replies 8 ·
Replies
8
Views
2K
Replies
10
Views
2K
  • · Replies 12 ·
Replies
12
Views
2K
  • · Replies 6 ·
Replies
6
Views
3K
  • · Replies 6 ·
Replies
6
Views
2K
  • · Replies 2 ·
Replies
2
Views
3K