printcols.c 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /*(c) Copyright Barry Kauler 2009*/
  2. /*Invoke like this: printcols afilename 1 6 2 9
  3. ...columns with '|' delimiter character get printed, in order specified.
  4. handles up to 15 columns.
  5. Designed for use in the Puppy Package Manager, puppylinux.com
  6. Compile statically:
  7. # diet gcc -nostdinc -O3 -fomit-frame-pointer -ffunction-sections -fdata-sections -fmerge-all-constants -Wl,--sort-common -Wl,-gc-sections -o printcols -o printcols printcols.c
  8. * OR
  9. * musl-gcc -static -O3 -fomit-frame-pointer -ffunction-sections -fdata-sections -fmerge-all-constants -Wl,--sort-common -Wl,-gc-sections -o printcols printcols.c
  10. *
  11. * then:
  12. * strip --strip-all -R .note -R .comment
  13. */
  14. #include <stdio.h>
  15. #include <string.h>
  16. #include <stdlib.h>
  17. #define BUF_SIZE (1024 * 1024 * 1)
  18. #define LINE_SIZE BUF_SIZE
  19. int main (int argc, char ** argv) {
  20. int cntargs;
  21. char *buffer1;
  22. char *buffer2;
  23. FILE* fp;
  24. char *ptokens[15];
  25. int i;
  26. int cnt;
  27. int max=0;
  28. int nextarg;
  29. int args[15];
  30. for (cntargs=2;cntargs<argc;++cntargs) {
  31. args[cntargs]=atoi(argv[cntargs]);
  32. if (cntargs==2) max=args[cntargs]; else max=args[cntargs]>max ? args[cntargs] : max;
  33. }
  34. buffer1 = malloc(LINE_SIZE);
  35. buffer2 = malloc(BUF_SIZE);
  36. fp = fopen(argv[1],"r");
  37. setbuffer(fp, buffer2, BUF_SIZE);
  38. while( fgets(buffer1,LINE_SIZE,fp) != NULL ) {
  39. cnt=1;
  40. ptokens[0]=buffer1;
  41. i=0;
  42. while (buffer1[i]!='\0' && cnt<=max) {
  43. if (buffer1[i]=='|') {
  44. buffer1[i]='\0';
  45. ptokens[cnt]=&buffer1[i+1];
  46. ++cnt;
  47. }
  48. ++i;
  49. }
  50. /*print the fields in requested order...*/
  51. for (cntargs=2;cntargs<argc;++cntargs) {
  52. nextarg=args[cntargs];
  53. if ( nextarg >= cnt ) { putc('|', stdout); continue; } /*in case of lines with less fields*/
  54. fputs(ptokens[nextarg - 1], stdout);
  55. putc('|', stdout);
  56. }
  57. putc('\n', stdout);
  58. }
  59. fclose(fp);
  60. free(buffer2);
  61. free(buffer1);
  62. return 0;
  63. }