When I compile this using GCC on linux, as I am waiting for input, the “hi” shows up. I do not want to use scanf, and want to know why the hi is showing while I am asking the user to input the name. Also when I want to printout the name of the file that was just passed, I get garbage characters. In netbeans, i get what I want. but on linux, it decides to act weirdly. please help
Code:
int main(int argc, char** argv)
{
char val[70];
if(write(1, "Please input your name", 36)!=36)
{
return -1;
}
if(read(0, val, 36) < 0)
{}
if(write(1, val, 36)!=36)
{}
printf("Yo");//THIS IS PRINTING OUT WAY BEFORE IT IS CALLED, ANY VARIABLE WITH A STRING GETS PRINTED OUT, EVEN WITHOUT PRINTF BEING INVOKED
}
output:
Please input the file nameYo: hi
hi
???Om?0?a?Sm? <<WHAT IS THIS? I DONT GET THIS ON NETBEANS
The third argument to
writeis the byte length of the string you’re trying to print. You have 36, but the string you provide is only 22 bytes long. Changing the code to look like the following will behave as you expected it to:Note that you should probably look into using
printfandscanfso that you wont have to worry about byte lengths so much.That might look like this: