Thread: reading X character from a file

  1. #1
    Registered User
    Join Date
    Jan 2005
    Posts
    4

    reading X character from a file

    I'm trying to read 4 characters from a file, and then output them to the screen.
    the file contains:
    abcdefgh


    This is my basic code:

    char *filename = "file.txt";
    char *line[5];

    FILE *fp = fopen(filename, "r");
    fread (line, sizeof(char), 4, fp);

    line[4] = '\0';
    printf("line: %s\n", line);

    The output is abcdW

    Why is the last character of my output always screwed up?
    My goal is to (eventually) read in 50 characters, print to screen, then read in another
    50 characters, etc.

    I just can't figure out why the 5th character which is supposed to be null, gets printed
    all scewed up.

    Thanks!

  2. #2
    Registered User
    Join Date
    Sep 2007
    Posts
    38
    Try initializing the line array.

  3. #3
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    Your first sign of something wrong:
    warning: char format, pointer arg (arg 2)
    You have, not an array of chars, but an array of char* s. Try char line[5]; instead.

  4. #4
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    char line[5];
    should be
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 7
    Last Post: 02-02-2009, 07:27 AM
  2. Basic text file encoder
    By Abda92 in forum C Programming
    Replies: 15
    Last Post: 05-22-2007, 01:19 PM
  3. Encryption program
    By zeiffelz in forum C Programming
    Replies: 1
    Last Post: 06-15-2005, 03:39 AM
  4. UNICODE and GET_STATE
    By Registered in forum C++ Programming
    Replies: 1
    Last Post: 07-15-2002, 03:23 PM
  5. System
    By drdroid in forum C++ Programming
    Replies: 3
    Last Post: 06-28-2002, 10:12 PM