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 stdin using the read() and not fgets and the like.
So I have a simple while loop:
int n, i;
char buffer[257], *input;
while((n=read(fileno(stdin), buffer, 256)) > 0)
{
buffer[n] ='\0';
if(buffer[n] = '\n') break;
write(input, buffer, strlen(buffer));
}
So I am not sure how to make this loop stop at the press of enter (end of line) so that's why I have the break code, though I don't know if that's done correctly.
The whole objective I am trying to accomplish is to put the input from stdin into the pointer 'input'
(I am really bad at understanding pointers so bear with me :) )
My problem is that I am getting segmentation faults when I press enter. I wish I could use fgets because then all this would be solved with a simple
input = fgets(buffer, 256, stdin);
Darn homework :( Anyways, if any of you could point me in the right direction, I would really appreciate it. Thank you!
You're going about it all wrong. Firstly,
write
is a system call that's used to write to a open file descriptor. Yourinput
is nothing like that - a file descriptor is gained by calling theopen
syscall first, or referring to one of the always-open files, e.g.stdin
,stdout
orstderr
. Not to mention that a file descriptor is anint
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 tostdin
), or the input from keyboard may simply end with aCtrl-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 byinput
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 thememcpy
function instead. Why don't you simply try reading directly intoinput
, though? It doesn't make much sense to read tobuffer
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 yourbuffer
is declared aschar[257]
, then you should callread(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.
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.