2017-08-30 9 views
2

から、未知の長さの入力を得るために、私はscanf()を使用しますが、私はを持っていないとことができ、この時間はread()を使用します。は読み使用方法()これまで標準入力

char buf[128]; 
read(0, buf, sizeof(buf)); 

がしかし、今回は私が入力する任意の長さの制限を持っていないと私は、任意のサイズの入力を許可する:

通常、readを使用してSTDINからの入力を取得するために私が使用しています。過去には、私は、このためのscanfを使用しそうのような:

char *user_input; 
scanf("%ms", &user_input); 

がどのように私はread()でこれを行うことができますか?
注:安全性はここでは重要ではありません

+3

基本的に1行を読むには、 '\ n'が出現するまで文字を1文字ずつ読みます。しかし、あなたは 'read'を使う必要がありますか? –

+0

'read(0、buf、sizeof(buf));' 'buf'がそれ以降の文字列を含むことを期待していないことを望みます。 –

+2

[recv()](http://man7.org/linux/man-pages/man2/recv.2.html)はPOSIX関数なので、変数名として 'recv'を使用しないでください。 –

答えて

-2

一つの方法は、ループgetchar関数()関数を実行し、配列に文字をrading維持されます。各繰り返しでアレイサイズを確認します。アレイがいっぱいになったら、それを大きなサイズに再割り当てします。または、getline()関数を使用します。 リンクgetline()

次のプログラムを確認してください。

#include <stdio.h> 
#include <stdlib.h> 
int main(void) { 
    char *lines = NULL; 
    size_t n = 0; 
    ssize_t res = getline(&line, &n, stdin); 
    free(line); 
} 
+1

これは答えよりもむしろコメントです。そして、彼は 'read'を使いたいと述べています。 –

1

機能readは、読み取りバイト数を返します。あなたは0バイトを読むまで、あなたはreadはないが自動的\0bufにヌルターミネータを追加し

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

注: 'read()'は-1を返すことができます。 – wildplasser

+0

@wildplasserそれは本当です。編集中... – ninjin

+0

注:* first * read()も-1を返す可能性があります。 (また:DRY) – wildplasser

関連する問題