Search code examples
cfgetc

Undefined characters in string after reading file with fgetc()


I'm trying to write a simple code in order to read the stdin then use it so I tried to type little program in order to put my stdin in a defined size table and it looks like this:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>

int main(int argc, char *argv[]){   
    int c , i = 0 ;
    char str[1024];

    while(c != EOF){
        c = fgetc(stdin);
        str[i]=c;
        i++;
    }
    printf("%s\n",str);
    return 0;
}

When I run the program with

$ test < file.json

I get:

{
    "num": 8
}�@/�

I can't explain the last four undefined characters. I'm guessing it's relative to the fgetc() pointer. I want to stop at the EOF.

I've looked everywhere, and I can't understand. I'm still learning C language, so my goal is to read the stdin which is a JSON file with the command

$ test < file.json

then use Jansson to extract and use the data, but my problem is reading the file with that command.


Solution

  • You need to null-terminate your string :

    while (c != EOF) {
        c = fgetc(stdin);
        str[i]=c;
        i++;
    }
    
    str[i] = '\0';
    

    And yes, you should initialize c prior to checking if it is EOF.