I have a quick little question involving the read() command.
I am really rusty in C, and unfortunately, my current assignment has me programming in C. We need to read st
Your input
dosn't point anywhere valid. You need to either allocate some memory (and free it when you're done) or make it point to valid storage.
Also =
is assignment; ==
is comparison.
You're going about it all wrong. Firstly, write
is a system call that's used to write to a open file descriptor. Your input
is nothing like that - a file descriptor is gained by calling the open
syscall first, or referring to one of the always-open files, e.g. stdin
, stdout
or stderr
. Not to mention that a file descriptor is an int
on Linux.
Also, you should remember that the assumption of your input on stdin
ending with a newline doesn't have to be right all the time. Your program may receive some content on standard input that doesn't contain any newlines, for example contents of some file (redirected to stdin
), or the input from keyboard may simply end with a Ctrl-D
(EOF) instead of the "return" key.
On top of all that, an uninitialized pointer doesn't refer to any valid memory. The declaration of char *input
doesn't give you any right to write/read the memory referred to by input
unless you allocate some memory that this pointer will point to first.
Copying strings in C is achieved by using functions declared in <string.h>
. They operate on C-strings, e.g. sequences of characters terminated by \0
. In this case, read()
doesn't terminate its output by a \0
, in which case you'll want to use the memcpy
function instead. Why don't you simply try reading directly into input
, though? It doesn't make much sense to read to buffer
first, simply to copy the data to another chunk of memory later on.
Also, the specification of read
states that it reads up to count bytes from the file descriptor. Which means that if your buffer
is declared as char[257]
, then you should call read(stdin,buffer,257)
, not 256. It would probably also be more suitable to simply declare the buffer as a 256-element array.
I hope that I've straightened out some stuff for you.