fork download
  1. #define _GNU_SOURCE
  2. #include <iso646.h> // and
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <string.h>
  6.  
  7. // max number of characters in a line including '\n' and '\0'
  8. const size_t maxline = 16;
  9.  
  10. int main() {
  11. FILE *fp = stdin; // read from stdin
  12. char line[maxline];
  13. char *str = NULL, *s = NULL;
  14. for (int i = 1; fgets(line, maxline, fp) != NULL; ++i) {
  15. const size_t n = strlen(line) + 1; // +1 for '\0'
  16. if (n == maxline and (maxline < 2 or line[maxline-2] != '\n')) {
  17. fprintf(stderr, "error: line #%d is too long: %s", i, line);
  18. exit(EXIT_FAILURE);
  19. }
  20. // if line starts with "name" and '=' is in the string
  21. const char* name = "name";
  22. if (strncmp(name, line, strlen(name)) == 0 and
  23. (s = strchr(line, '=')) != NULL) {
  24. str = strdup(s+1); // copy everything after the first '='
  25. if (str == NULL) {
  26. perror("strdup");
  27. exit(EXIT_FAILURE);
  28. }
  29. printf("line #%d: name: %s", i, str);
  30. break;
  31. }
  32. }
  33. // do other stuff with `str` here
  34. // ...
  35. free(str);
  36. }
Success #stdin #stdout 0.02s 1856KB
stdin
1
2
3
4
name=Meli She;
6
7
8
9
loooooooooooooooooooooooooooooooooooooooooooooooooooooooooong line
stdout
line #5: name: Meli She;