1. Computing & Technology

Discuss in my forum

C Programming Tutorial - Text File Handling

By , About.com Guide

1 of 10

What is a Text File?
This C programming tutorial is about Text Files and a followup to the previous one on Random Access Files. Technically you can do random access with text files (as opposed to binary) so long as you open the text file in binary mode. There is virtually no difference between a text file and a binary file except that the binary file can hold all byte values and the text file is restricted to a subset. They are both just a collection of bytes stored on disk. How you process them is the real difference. We've seen how to process a binary file and in this tutorial we see how to handle a text file.

What is a Text File?

For simplicity, I'm not considering Unicode in this tutorial. We're staying in the 7 bit world of ASCII so the highest character code is 127. A text file is a file that holds ASCII characters organised in multiple length lines separated by a line break. ASCII character includes
  • 0x7 (bell)
  • 0x8 (backspace)
  • 0x9 (tab)
  • 0xa (line feed)
  • 0xc (Form Feed) Not used so much nowadays
  • 0xd (carriage return)
  • All characters in the range 0x20 (space) through to 0x7f.
This short example prints out the characters and their values.

 // ex1.c 
 
 #include <stdio.h>
 int main(int argc, char * argv[])
 {
   int i;
     char c;
     for (i=0x20;i<0x80;i++)
    {
     c = i;
     printf("Char %d = %c\n\r",i,c) ;
     if (((i+1) % 16)==0)
       printf("\n\r") ;
   }
   return 0;
 }
 

On the next page : Structure of Text Files

©2012 About.com. All rights reserved.

A part of The New York Times Company.