• Advertisement

Archived

This topic is now archived and is closed to further replies.

Binary reading

This topic is 5536 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Advertisement

    
#include <stdio.h>

int main(int argc, char** argv)
{
FILE* fp; // Handle to the file you will be reading from

int ch; // Will hold the value we read in from the file


// Try to open the file with binary read access

// "rb" --> r=read b=binary

if(NULL == (fp = fopen("samplefile.dat","rb")))
{
printf("Error: Couldn't open file samplefile.dat");
return 1;
}

// If we got this far, it means we have a valid file handle (fp)

// There are different ways to access the contents of the file --

// you might be interested in looking up the functions "fread".

// In this example, we will step through each BYTE of the file

// until we reach its end:


// Get the next value in the file, and put it in the variable "ch"

// until we reach the EOF (end of file). (note, "ch" is an int and not

// a byte, because the EOF constant is outside of byte range)

while(EOF != (ch = getc(fp)))
{
// Manipulate the data in any way you want here

// We will just echo it back to the screen


putchar(ch);
}

// Now all we need to do is release our handle of the file

fclose(fp);

return 0;
}


If you are interested specifically in the "binary" (1s and 0s), you can test the value of each byte you read in using "&" and a mask. As in:

ch & 0x0001

[edited by - frigidhelix on December 23, 2002 4:12:32 PM]

Share this post


Link to post
Share on other sites

  • Advertisement