read_stdin_line() - misc function in examples 01/70801/3
authorLukasz Pawelczyk <l.pawelczyk@samsung.com>
Wed, 18 May 2016 12:06:55 +0000 (14:06 +0200)
committerKrzysztof Jackiewicz <k.jackiewicz@samsung.com>
Fri, 27 May 2016 10:12:40 +0000 (12:12 +0200)
Useful e.g. to read passwords for the purpose of examples.

Change-Id: I75ba71667625ca9ffeae5ee288ac3b5c74053879

examples/misc.c
examples/misc.h

index 892da72..1846d5e 100644 (file)
@@ -21,6 +21,8 @@
  * @brief
  */
 
+#define _POSIX_C_SOURCE 200809L
+
 #include <stdio.h>
 #include <stdarg.h>
 #include <string.h>
@@ -126,3 +128,30 @@ int read_file(const char *path, char **data, size_t *data_len)
        free(buf);
        return ret;
 }
+
+int read_stdin_line(const char *prompt, char **string)
+{
+       char *buf = NULL;
+       char *ret;
+       size_t size;
+       ssize_t read;
+
+       if (prompt != NULL)
+               printf("%s", prompt);
+
+       read = getline(&buf, &size, stdin);
+       if (read <= 0) {
+               free(buf);
+               return -1;
+       }
+
+       ret = yaca_realloc(buf, read);
+       if (ret == NULL) {
+               free(buf);
+               return -1;
+       }
+       buf[read - 1] = '\0';
+
+       *string = buf;
+       return 0;
+}
index 7d89758..6eaa12f 100644 (file)
@@ -41,4 +41,6 @@ int write_file(const char *path, char *data, size_t data_len);
 
 int read_file(const char *path, char **data, size_t *data_len);
 
+int read_stdin_line(const char *prompt, char **string);
+
 #endif /* MISC_H */