1. Home
  2. Computing & Technology
  3. C / C++ / C#

C Programming Tutorial - Random Access File Handling

By , About.com Guide

2 of 9

Programming With Binary Files

A binary file is a file of any length that holds bytes with values in the range 0 to 0xff. (0 to 255). These bytes have no other meaning unlike in a text file where a value of 13 means carriage return, 10 means line feed, 26 means end of file and software reading text files has to deal with these.

In modern terms we call binary files a stream of bytes and more modern languages tend to work with streams rather than files. The important part is the data stream rather than where it came from! In C you can think about the data either in terms of files or streams. Or if it helps, think of a file/stream as a very long array! With random access you can read or write to any part of this array. With sequential you have to loop through it from the start like a big tape.

Download Example 1.

This shows a simple binary file being opened for writing, with a text string (char *) being written into it. Normally you'd use a text file for that but I wanted to show that you can write text to a binary file.

// ex1.c
#include <stdio.h>
#include <string.h>

int main(int argc, char * argv[])
{
  const char * filename="test.txt";
  const char * mytext="Once upon a time there were three bears.";
  int byteswritten=0;
  FILE * ft= fopen(filename, "wb") ;
  if (ft) {
    fwrite(mytext,sizeof(char),strlen(mytext), ft) ;
    fclose( ft ) ;
  }
  printf("len of mytext = %i ",strlen(mytext)) ;
  return 0;
}

On the next page : How Example 1 Works

Explore C / C++ / C#
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C
  5. C Tutorials
  6. Programming With Binary Files

©2009 About.com, a part of The New York Times Company.

All rights reserved.