Skip to content

Commit bf15dbf

Browse files
committed
examples: network: fix Win32 linking errors due to getline
The getline(3) function call is not part of ISO C and, most importantly, it is not implemented on Microsoft Windows platforms. As our networking example code makes use of getline, this breaks builds on MSVC and MinGW. As this code wasn't built prior to the previous commit, this was never noticed. Fix the error by instead implementing a `readline` function, which simply reads the password from stdin until it reads a newline character.
1 parent 0b98a66 commit bf15dbf

File tree

1 file changed

+39
-2
lines changed

1 file changed

+39
-2
lines changed

examples/network/common.c

Lines changed: 39 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,43 @@
1616
# define UNUSED(x) x
1717
#endif
1818

19+
static int readline(char **out)
20+
{
21+
int c, error = 0, length = 0, allocated = 0;
22+
char *line = NULL;
23+
24+
errno = 0;
25+
26+
while ((c = getchar()) != EOF) {
27+
if (length == allocated) {
28+
allocated += 16;
29+
30+
if ((line = realloc(line, allocated)) == NULL) {
31+
error = -1;
32+
goto error;
33+
}
34+
}
35+
36+
if (c == '\n')
37+
break;
38+
39+
line[length++] = c;
40+
}
41+
42+
if (errno != 0) {
43+
error = -1;
44+
goto error;
45+
}
46+
47+
line[length] = '\0';
48+
*out = line;
49+
line = NULL;
50+
error = length;
51+
error:
52+
free(line);
53+
return error;
54+
}
55+
1956
int cred_acquire_cb(git_cred **out,
2057
const char * UNUSED(url),
2158
const char * UNUSED(username_from_url),
@@ -26,14 +63,14 @@ int cred_acquire_cb(git_cred **out,
2663
int error;
2764

2865
printf("Username: ");
29-
if (getline(&username, NULL, stdin) < 0) {
66+
if (readline(&username) < 0) {
3067
fprintf(stderr, "Unable to read username: %s", strerror(errno));
3168
return -1;
3269
}
3370

3471
/* Yup. Right there on your terminal. Careful where you copy/paste output. */
3572
printf("Password: ");
36-
if (getline(&password, NULL, stdin) < 0) {
73+
if (readline(&password) < 0) {
3774
fprintf(stderr, "Unable to read password: %s", strerror(errno));
3875
free(username);
3976
return -1;

0 commit comments

Comments
 (0)