Source code of Windows XP (NT5)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

109 lines
2.3 KiB

  1. /* head - first n lines to STDOUT
  2. *
  3. * 20-Jul-1991 ianja Wrote it.
  4. * 21-Jul-1991 ianja Close stdin (for piped input)
  5. */
  6. #include <stdio.h>
  7. #include <stdlib.h>
  8. #include <string.h>
  9. #include <windows.h>
  10. int Head(char *pszFile, int nLines, BOOL fBanner);
  11. char *Version = "HEAD v1.1 1991-06-20:";
  12. #define BUFSZ 256
  13. void
  14. __cdecl main (argc, argv)
  15. int argc;
  16. char *argv[];
  17. {
  18. int nArg;
  19. int cLines = 10; // default
  20. int nFiles = 0;
  21. int nErr = 0;
  22. if ((argc > 1) && ((*argv[1] == '-') || (*argv[1] == '/'))) {
  23. if (argv[1][1] == '?') {
  24. printf("%s\n", Version);
  25. printf("usage: HEAD [switches] [filename]*\n");
  26. printf(" switches: [-?] display this message\n");
  27. printf(" [-n] display top n lines of each file (default 10)\n");
  28. exit(0);
  29. }
  30. cLines = atoi(argv[1]+1);
  31. nArg = 2;
  32. } else {
  33. nArg = 1;
  34. }
  35. nFiles = argc - nArg;
  36. if (nFiles < 1) {
  37. nErr += Head(NULL, cLines, FALSE);
  38. } else while (nArg < argc) {
  39. nErr += Head(argv[nArg], cLines, (nFiles > 1));
  40. nArg++;
  41. }
  42. if (nErr) {
  43. exit(2);
  44. } else {
  45. exit(0);
  46. }
  47. }
  48. int Head(char *pszFile, int nLines, BOOL fBanner)
  49. {
  50. FILE *fp;
  51. int nErr = 0;
  52. char buff[BUFSZ];
  53. /*
  54. * Open file for reading
  55. */
  56. if (pszFile) {
  57. if ((fp = fopen(pszFile, "r")) == NULL) {
  58. fprintf(stderr, "HEAD: can't open %s\n", pszFile);
  59. return 1;
  60. }
  61. } else {
  62. fp = stdin;
  63. }
  64. /*
  65. * Banner printed if there is more than one input file
  66. */
  67. if (fBanner) {
  68. fprintf(stdout, "==> %s <==\n", pszFile);
  69. }
  70. /*
  71. * Print cLines, or up to end of file, whichever comes first
  72. */
  73. while (nLines-- > 0) {
  74. if (fgets(buff, BUFSZ-1, fp) == NULL) {
  75. if (!feof(fp)) {
  76. fprintf(stderr, "HEAD: can't read %s\n", pszFile);
  77. nErr++;
  78. goto CloseOut;
  79. }
  80. break;
  81. }
  82. if (fputs(buff, stdout) == EOF) {
  83. fprintf(stderr, "can't write output\n");
  84. nErr++;
  85. goto CloseOut;
  86. }
  87. }
  88. if (fBanner) {
  89. fprintf(stdout, "\n");
  90. }
  91. CloseOut:
  92. fclose(fp);
  93. return nErr;
  94. }