I am writing a program to read stdin and output it.
int main() {
FILE* inputF = stdin;
char* inputStr[10];
fread(inputStr, 1, 9, inputF);
if(ferror(inputF)) {
printf("An error occurred");
return 0;
}
inputStr[9] = '\0';
printf("%s", (const char*)inputStr);
return 0;
}
It should create a 10 character long string and read 9 bytes of stdin into it, and then put '\0' in position 9.
When I run the program, this is the result:
gab@testvm:~/work/c/fibo$ ./a.out < test.txt
56 `ô
ga
Two lines and excess characters are printed (scroll to the right to see them).
What might be causing this?
@DanielFischer has pointed out your immediate problem, however once you’ve fixed the
char[]vschar*[]issue, you should also note…If
test.txtcontains fewer than 9 characters then the you will still have junk characters between the last read character and the position where your write the null terminator.You should check the return value of
freadto see how many characters were read and write the null terminator in the appropriate place.