Showing posts with label linux. Show all posts
Showing posts with label linux. Show all posts

Thursday, June 16, 2022

Head Or Tail 4/100

 Day 4/100 Head or Tail

I want them both!


I've always wanted to have my own head and tail program. The reason being is that so I can control exactly where the cutoff line would be. Right now, if I wanted a certain line in the middle, I have to pipe head into tail. I wanted my own file slicing program, so to speak. And here it is...


I think the first thing you notice would be the fact that there's a help instruction on the program. That is because I design it to be used. Granted it's not perfect. Array of pointers have a fixed size, and no WARNING available when the limit is exceeded. Also, the only input available is via stdin. 


Another noticeable feature would be the DEBUG option. It has helped me greatly as several instances of SEGMENTATION FAULT occurred while I was developing the program. Heh. And given the lack of sophisticated error message does make it a bit harder to figure out. Would you believe the biggest stumble was in printf()? I was still shaking my head on that one...


The name of the program is HeadOrTail, and it is because the program features both options. And rightly so, because they both are similar in size and features. Or rather, HEAD is very easy to write, while TAIL is very hard to write due to the need of dynamic memory allocations. I cheated a bit and use the recursive feature of the C language to do it. It does complicated matter, and I had to build my own stack to simulate QUEUE. Sigh.


Still not too bad. Not counting code for input, it's only 1 line for HEAD, and 3 lines for TAIL. Now that's neat! Recursion to the max for the win!


So, yes, the program works, and it's usable. That's what matters. The fact that it's done in about 3 hours or so, including this write up is a nice bonus.


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int HeadOn=0;
int HeadOf=0;
int TailOn=0;
int TailOf=0;
int Debug=0;
#define MAXARR 65535
char *StrArr[MAXARR]; //For Tail
int tstackptr=0;

void ShowMsg() {
    puts("Usage: hot [OPTION]...");
    puts("Head or Tail prints both head lines and tail lines.");
    puts("It takes stdin as input.");
    puts("If options are not specified, it prints nothing.");
    puts("  -hNUM   print the first NUM lines of each input.");
    puts("  -HNUM   skip the first NUM lines of each input.");
    puts("  -tNUM   print the last NUM lines of each input.");
    puts("  -TNUM   skip the last NUM lines of each input.");
    puts("  --help  print this message.");
    puts("  --debug show debug messages.");
    puts("\nExample:");
    puts("  hot -h10 -H5 -t20 -T15\n");
    puts("  The above example will print the first 10 lines,");
    puts("  EXCEPT the first 5 lines (i.e. 6-10).");
    puts("  It will also print the last 20 lines,");
    puts("  EXCEPT the last 15 lines.");
}
int GetOpt(int argc, char *argv[]) {
int i;
  for (i=1;i<argc;i++) {
    if (!strncmp("-h",argv[i],2)) HeadOn=atoi(argv[i]+2);
    if (!strncmp("-H",argv[i],2)) HeadOf=atoi(argv[i]+2);
    if (!strncmp("-t",argv[i],2)) TailOn=atoi(argv[i]+2);
    if (!strncmp("-T",argv[i],2)) TailOf=atoi(argv[i]+2);
    if (!strncmp("--help",argv[i],6)) ShowMsg();
    if (!strncmp("--debug",argv[i],7)) Debug=1;
  }
  if (Debug) {
    printf("HeadOn =%d\n",HeadOn);
    printf("HeadOff=%d\n",HeadOf);
    printf("TailOn =%d\n",TailOn);
    printf("TailOff=%d\n",TailOf);
  }
  return 0;
}
void PushStk(char *buffer, size_t size) {
  if (Debug) puts("PushStk start");
  StrArr[tstackptr] = (char *) malloc(size);
  strcpy(StrArr[tstackptr],buffer);
  tstackptr++;
  if (Debug) puts("PushStk end");
}
void PopStk() {
  while (0<tstackptr--) {
    printf("%s",StrArr[tstackptr]);
    free(StrArr[tstackptr]);
  }
}

int HeadOrTail(int linenum) {
  char *buffer=NULL; size_t bufLen=0;
  ssize_t bufSize=0; int r,maxnum;
     maxnum=linenum;
  bufSize=getline(&buffer, &bufLen, stdin);  
  if (linenum<=HeadOn && linenum>HeadOf)
    printf("%s",buffer);
  if (bufSize>0) {
    r=(maxnum=HeadOrTail(linenum+1))-linenum;
    if (r<=TailOn && r>TailOf
    && linenum < MAXARR) PushStk(buffer,bufSize);
  } 
  free(buffer); return maxnum;
 }

int main (int argc, char *argv[] ) {
  int e=0;
  if   (argc<2) { ShowMsg(); return 0; }
  GetOpt(argc, argv);
  e=HeadOrTail(1);
  PopStk();
  return e;
}


One final note: Would you believe I got hung up because I put semi-colon on my #define? SMH.


Friday, November 6, 2020

DIY Typing Tutor in Bash

 


So, when somehow the 10fastfingers.com broke on me, I was left with no good way to practice typing. Well, I decided to write my own. Using BASH. That's shell scripting. 

I learned quite a bit about shell scripting, but there's more to do still. The biggest problem is not the coding. Actually, the biggest time sink is the design. I'm on my third design and still going on. 

The whole scripts is only about 4K. So, recreating this should only take an enjoyable afternoon. There's some advanced manipulation there, though.

Since this is done on Raspberry pi, I use pdftotext to extract texts to create my dictionary.  Turns out it's relatively quick, even on my RaspiZero. 100 most popular Project Gutenberg texts, however, took about 20 minutes to process all dictionary, the longest being top 100, 200 most common words.

I will update this later. I got some ideas about vt100 terminal cursor manipulation. 


Thursday, February 6, 2014

Book Review #22


Book #22 Programming Linux Games
John R. Hall

Programming Linux Games is an old, old book. In fact, it's obsolete. The reason is that SDL has evolved toward a better set, and some of the functions are deprecated. In addition, it uses plain old C language, that although a great language to use, it has been superceeded by C++, and Java, among other languages. Still, there's enough similarities between this book and current SDL that it's a great introduction to the process of SDL programming.

One of my most frustrating endeavor is finding the proper answer to my question regarding any graphic library: "How do you draw a point on screen?"

That one very simple question is frequently unanswered in great many graphical programming book. I know that's silly, but there you go. This book answers the question right away: Using surface.

"Each SDL_Surface structure contains a pixels member. This is a void * to the raw image, and we can write to it directly if we know the type of pixel that the surface is set up for."

And upon those two sentences, I bought the whole book!

It's a good book, marred only by the fact that it's so old, it's obsolete. However, reading this book followed by reading SDL man pages is infinitely preferable to just going straight on without guidance. The explanations are solid, and adapting the code to newer system is not a problem.

FYI, the ever popular PyGame extension for Python uses SDL for the base. SDL is a good graphic library to learn, especially if you're really interested in harnessing the speed and efficiency of C language.

For those of you still stuck with C programming, give this book a read. You just may like what you see.

Thursday, October 17, 2013

Book Review #6


The Linux Command Line
William E. Shotts, Jr

I've been looking for a good shell scripting book when I chance upon this book. Reading the book gives me a good understanding, not only in scripting capabilities, but also the standard Linux shell programs. Things like lp, cat, grep, and sed are explored in details. I have come to the understanding that, in fact, I need this book more than anything. In my work with Raspberry Pi, I am dealing with Linux command line every day. I'm happy to say that I have written a few significant shell scripts that do not rely on powerful scripting language such as Perl or Python. Although the resulting scripts run slower, I don't mind at all. It's the learning process that matters.

In regard to Raspberry Pi, it is a great enabler device. However, I am with the opinion that a great enabler device by itself is not enough. I have numerous books about making this project or that project with Raspberry Pi. However, in the process of making the project, I have often come into the stumbling blocks of every day occurence. How do I format SD card? How to disable the screensaver? And so on. This book not only explains all the tools you need in order to navigate the Linux shell, but also gives you the powerful bash scripting technique that you can use to whip up a quick script leveraging the various Linux shell programs.

This is just my opinion, but I think this book is a must have for all Raspberry Pi users, if not all Linux users. Highly Recommended.

Thursday, September 26, 2013

Raspberry Pi Journal #29

BASH Scripting


As you may know, Python is the officially supported programming language of Raspberry Pi. What you may not know is that the Raspbian shell is bash, Born/Bourne Again Shell. Bash is a more sophisticated version of sh. There is also csh, and other flavor, if you're interested.

That's why, you frequently see "#!" shebang format for script language. That has special meaning to run the program specified and feed it the content of the file. That's right. A Python script is just a program that interprets the file's content. Pretty convenient, eh?

So, what does that have to do with bash? If you're used to Windows shell, probably not much. But if you look at the documentation for bash, man bash, you'll see that it is rather involved.

Shell scripting isn't strictly computer programming, although the nuance may be lost to inexperienced coder. If you know Perl, that language was designed to act as a glue language for various programs. So, the relationship would be bash-perl-program.

And Perl is very convenient to use. I use it a lot in the past. However, sometimes you don't need the full brunt of full-featured scripting language. bash is a viable lightweight alternative.

I'm not that good of a coder with bash. Still, it is something you should learn. There was a job description that says something like:

The applicant must know Unix shell programming, but sufficiently advanced enough to realize that it is not an achievement.

In other words, shell scripting is not a proper computer programming. It is a "convenient" tool.

Let me just point to you a nice resource that I found on the web, and I happily read it. I hope you do too.

http://tille.garrels.be/training/bash/

You need to know Linux already, but for those of you who do, this is a great resource.