Thread: displaying contents of a text file

  1. #1

    Question displaying contents of a text file

    Hello folks,

    the following program will simply read whats inside test.txt and will display that on the screen. However, it will also print the ascii value for the empty line that follows the text. Could you please tell me what i should be doing in order to have the text as the only output on the screen (after all, is this a good way of displaying my file anyways?)

    Also, what if i am working with binary files. how can i display the contents of such files?


    #include <stdio.h>


    FILE *ptr;
    char ch;
    ptr = fopen("test.txt","r+");
    if (ptr==NULL)
    printf("Error: File does not exist\n\n");
    while(ch != EOF);

  2. #2
    The Artful Lurker Deckard's Avatar
    Join Date
    Jan 2002

    Re: displaying contents of a text file

    Originally posted by Unregistered
    Also, what if i am working with binary files. how can i display the contents of such files?
    Normally, binary files are printed as a hex dump. You can represent a single character as hex with the conversion code %2x.

    As to your other question, I'm a little vague on what you consider the problem. If you don't want the EOF to be printed to the screen, you should test the value of 'ch' prior to printing it.
    Jason Deckard

  3. #3
    Registered User
    Join Date
    Jan 2002

    just to expand further

    I agree just test the value of ch...

    something like this should work groovy..

    while( read(file, &ch, 1) > 0 ){
    if( ch == EOF ){
    // do nothing
    if( ( ch > 31) && ( ch < 127 )){ // ascii chars
    printf(" %c", ch);
    printf(" %02X", ch); // non printable chars

    ~good monkeys, Excelent typewritters!...

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    > putchar(ch=getc(ptr));
    You should test ch for EOF, after doing getc, and before doing putchar

    Otherwise, you will output the "cast-to-char" value of EOF

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. storing text file contents into a string
    By m.mixon in forum C Programming
    Replies: 4
    Last Post: 07-20-2006, 11:52 AM
  2. Batch file programming
    By year2038bug in forum Tech Board
    Replies: 10
    Last Post: 09-05-2005, 03:30 PM
  3. struct question
    By caduardo21 in forum Windows Programming
    Replies: 5
    Last Post: 01-31-2005, 04:49 PM
  4. Possible circular definition with singleton objects
    By techrolla in forum C++ Programming
    Replies: 3
    Last Post: 12-26-2004, 10:46 AM
  5. Outputting String arrays in windows
    By Xterria in forum Game Programming
    Replies: 11
    Last Post: 11-13-2001, 07:35 PM