Advertisement
Guest User

Untitled

a guest
Jun 26th, 2019
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.84 KB | None | 0 0
  1. "%*d|%s|%*s|%s|%*d|%*s|%*d|%*s|%*s|%*f|%*f|%*s|%*s|%*f|%*f"
  2.  
  3. #include <stdio.h>
  4. #include <string.h>
  5.  
  6. #define FLDW 32 /* max field width */
  7. #define MAXC 1024 /* max chars in line */
  8.  
  9. int main (int argc, char **argv) {
  10.  
  11. char buf[MAXC], /* line buffer */
  12. name[FLDW], /* storage for name */
  13. state[FLDW]; /* storage for state */
  14.  
  15. /* use filename provided as 1st argument (stdin by default) */
  16. FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;
  17.  
  18. if (!fp) { /* validate file open for reading */
  19. perror ("file open failed");
  20. return 1;
  21. }
  22.  
  23. while (fgets (buf, MAXC, fp)) { /* read each line of input */
  24. /* parse 2nd & 4th fields as strings - you don't care about rest */
  25. if (sscanf (buf, "%*d|%31[^|]|%*[^|]|%31[^|]", name, state) == 2) {
  26. buf[strcspn (buf, "n")] = 0; /* trim n from buf */
  27. /* output line with parsed name and state to right */
  28. printf ("%s => name: %s, state: %sn", buf, name, state);
  29. }
  30. }
  31. if (fp != stdin) fclose (fp); /* close file if not stdin */
  32.  
  33. return 0;
  34. }
  35.  
  36. $ ./bin/fgetssscanf dat/field15pipes.txt
  37. 01|8a|0b|6c|82|1d|33|5e|4f|7.|0.|4g|3h|7.|5. => name: 8a, state: 6c
  38. 01|9a|5b|0c|42|1d|93|3e|9f|8.|0.|5g|4h|6.|5. => name: 9a, state: 0c
  39. 01|4a|5b|7c|22|0d|23|1e|1f|7.|2.|1g|5h|7.|7. => name: 4a, state: 7c
  40. 01|8a|2b|5c|72|1d|53|6e|2f|1.|1.|8g|0h|7.|6. => name: 8a, state: 5c
  41. 11|4a|6b|5c|92|2d|73|0e|6f|4.|2.|2g|7h|2.|4. => name: 4a, state: 5c
  42. 01|2a|6b|0c|02|1d|83|0e|2f|5.|2.|9g|4h|3.|8. => name: 2a, state: 0c
  43. 31|1a|0b|0c|72|2d|13|3e|3f|9.|0.|2g|5h|6.|9. => name: 1a, state: 0c
  44. 01|8a|3b|7c|92|1d|93|3e|9f|6.|1.|4g|4h|8.|3. => name: 8a, state: 7c
  45. 11|1a|4b|7c|42|2d|73|0e|5f|7.|0.|0g|5h|1.|7. => name: 1a, state: 7c
  46. 21|8a|6b|9c|22|2d|23|2e|1f|9.|0.|1g|6h|6.|8. => name: 8a, state: 9c
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement