機能read
は、読み取りバイト数を返します。あなたは0バイトを読むまで、あなたはread
がはないが自動的\0
buf
にヌルターミネータを追加し
char buf[BUF_SIZE]; // Set BUF_SIZE to the maximum number of character you expect to read (e.g. 1000 or 10000 or more).
int bytes_to_read, total_read_bytes, read_bytes;
// Number of bytes to read at each iteration of the loop.
bytes_to_read = 128;
// The following variable counts the number of total read bytes.
total_read_bytes = 0;
while ((read_bytes = read(0, buf + total_read_bytes, bytes_to_read) != 0) {
if (read_bytes < 0) {
// read() may return -1. You can look at the variable errno to
// have more details about the cause of the error.
return -1;
}
total_read_bytes += read_bytes;
}
お知らせことread
戻り0、つまり、この情報およびループを利用することができ、つまり、buf
ですあなたが明示的にそれの末尾に\0
を追加するまで、文字列ではありません。
...
// Making buf a string.
buf[total_read_bytes] = '\0';
...
基本的に1行を読むには、 '\ n'が出現するまで文字を1文字ずつ読みます。しかし、あなたは 'read'を使う必要がありますか? –
'read(0、buf、sizeof(buf));' 'buf'がそれ以降の文字列を含むことを期待していないことを望みます。 –
[recv()](http://man7.org/linux/man-pages/man2/recv.2.html)はPOSIX関数なので、変数名として 'recv'を使用しないでください。 –