Thread: how do i read two bytes in a row?

  1. #1
    Registered User
    Join Date
    Nov 2016
    Posts
    18

    how do i read two bytes in a row?

    hi first look at this code:
    Code:
    #include <stdio.h>
    #include <stdlib.h>
      
    void binary(char byte) {
        unsigned char mask = 0x80;
        for ( ; mask; mask >>= 1)
            putchar(byte & mask ? '1' : '0');
    }
     
    int main( void )
    {
        FILE *fp;
        int c;
      
        if ( (fp = fopen("TEXT.TXT", "rb")) == NULL)
        {
            fprintf(stderr, "Error opening file.");
            exit(1);
        }
     
        while ((c = fgetc(fp)) != EOF)
        {
            binary(c);
            putchar(' ');
        }
     
        putchar('\n');
        fclose(fp);
        return 0;
    }
    fgetc reads fp one byte at a time but how can i read two bytes in a row and save them to arrays like this: first and second byte in c[0] and c[1] and after code is executed third and fourth byte in c[0] and c[1] and on... . ( the code was just for example )

  2. #2
    Programming Wraith GReaper's Avatar
    Join Date
    Apr 2009
    Location
    Greece
    Posts
    2,738
    What you need is a standard function called fread(). Visit the link to see how it works.
    Devoted my life to programming...

  3. #3
    Registered User
    Join Date
    Jun 2015
    Posts
    1,640
    Just use two fgetc's in a row.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 6
    Last Post: 02-08-2012, 06:54 PM
  2. bytes lost with partial read in UDP
    By mynickmynick in forum Networking/Device Communication
    Replies: 3
    Last Post: 03-31-2009, 02:06 AM
  3. read 2 bytes from a file...
    By compile in forum C Programming
    Replies: 10
    Last Post: 10-17-2006, 12:54 AM
  4. Max number of bytes for a read file
    By NewGuy100 in forum C Programming
    Replies: 2
    Last Post: 08-18-2005, 06:37 AM
  5. How can I know the actual bytes read in a file read
    By pliang in forum C++ Programming
    Replies: 1
    Last Post: 06-08-2005, 04:23 PM

Tags for this Thread