last character of a string - in C

Discussion in 'C' started by endfx, Feb 5, 2008.

  1. endfx

    endfx New Member

    Feb 5, 2008
    Likes Received:
    Trophy Points:
    I'm trying to read 4 characters from a file, and then output them to the screen.
    the file contains:

    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.

  2. oogabooga

    oogabooga New Member

    Jan 9, 2008
    Likes Received:
    Trophy Points:
    You want char line[5] for an array of chars. You are declaring an array of pointers to chars then reading 4 bytes into the first pointer and storing zero in the last pointer then passing the address of the first pointer to printf (with %s) and it prints chars until it happens to find a zero.

    Also, sizeof(char) is always 1 since the sizeof operator returns sizes in multiples of the size of a char (which I believe is supposed to represent the smallest addressable unit of memory on the machine, which on PCs is 1 8-bit byte).

    fgets is more appropriate for reading chars.

    P.S., remember to use a code block next time to properly display your code.

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice