C - Write the program tail which prints the last n lines of its input

素颜马尾好姑娘i 2022-11-14 11:52 142阅读 0赞

分享一个大牛的人工智能教程。零基础!通俗易懂!风趣幽默!希望你也加入到人工智能的队伍中来!请点击http://www.captainbed.net

  1. /*
  2. * Write the program tail, which prints the last n lines of its input. By default,
  3. * n is set to 10, let us say, but it can be changed by an optional argument so that
  4. * tail -n
  5. * prints the last n lines. The program should behave rationally no matter how
  6. * unreasonable the input or the value of n. Write the program so it makes the best
  7. * use of available storage.
  8. *
  9. * Tail.c - by FreeMan
  10. */
  11. #include <stdio.h>
  12. #include <stdlib.h>
  13. #define MAXLINES 1024
  14. #define MAXINPUT 10240
  15. #define DEF_NUM_LINES 10
  16. int getlines(char *);
  17. void parse_args(int, char **);
  18. char linestr[MAXINPUT];
  19. char *lineptr[MAXLINES];
  20. int num_of_lines = DEF_NUM_LINES;
  21. int main(int argc, char *argv[])
  22. {
  23. int lines;
  24. int ltp = 0;
  25. int i;
  26. int c;
  27. *lineptr = linestr;
  28. /* Parse the argument strings passed to the program */
  29. if (argc > 1) {
  30. parse_args(argc, argv);
  31. }
  32. /* Get the input from the user */
  33. lines = getlines(linestr);
  34. if (num_of_lines == 0) {
  35. num_of_lines = 10;
  36. }
  37. ltp = lines < num_of_lines ? lines : num_of_lines;
  38. printf("\n>>> Printing %d line(s):\n", ltp);
  39. if (ltp == DEF_NUM_LINES) {
  40. printf(">>> The default number of lines to print is ");
  41. printf("%d\n", DEF_NUM_LINES);
  42. }
  43. printf("\n");
  44. for (i = lines; i > 0; i--)
  45. {
  46. while ((c = *lineptr[0]++) != '\n')
  47. {
  48. if (i <= ltp)
  49. {
  50. printf("%c", c);
  51. }
  52. }
  53. if (c == '\n' && i <= ltp)
  54. {
  55. printf("\n");
  56. }
  57. }
  58. return 0;
  59. }
  60. int getlines(char *buffer)
  61. {
  62. int i, count = 0;
  63. char c;
  64. for (i = 0; (c = getchar()) != EOF && i < MAXINPUT; i++) {
  65. *buffer++ = c;
  66. if (c == '\n') {
  67. lineptr[++count] = buffer;
  68. }
  69. }
  70. *buffer++ = '\0';
  71. return count;
  72. }
  73. void parse_args(int argc, char **argv)
  74. {
  75. char c;
  76. while (--argc > 0 && (*++argv)[0] == '-') {
  77. c = *++argv[0];
  78. switch (c) {
  79. case 'n':
  80. num_of_lines = atoi(*(argv + 1));
  81. break;
  82. }
  83. }
  84. }

发表评论

表情:
评论列表 (有 0 条评论,142人围观)

还没有评论,来说两句吧...

相关阅读