Try normal Linux programming Part 7

It seems to be a famous book so I bought it <a target="_blank" href="https://www.amazon.co.jp/gp/product/4797328355/ref=as_li_tl?ie=UTF8&camp=247&creative=1211&creativeASIN=4797328355&linkCode=as2&tag=lespacetranqu-22&linkId=b690c3257ff896f2239f1107e > Ordinary Linux programming The royal road of gcc programming that can be learned from the mechanism of Linux <img src = "// ir-jp.amazon-adsystem.com/e/ir?t=lespacetranqu-22&l=am2&o=9&a=4797328355" "width =" 1 "height =" 1 "border =" 0 "alt =" "style =" border: none! Important; margin: 0px! Important; "/> <a target="_blank" href="https://www.amazon.co.jp/gp/product/B075ST51Y5/ref=as_li_tl?ie=UTF8&camp=247&creative=1211&creativeASIN=B075ST51Y5&linkCode=as2&tag=lespacetranqu-22&linkId=aa0915aa60a5a > Ordinary Linux programming 2nd edition: The royal road of gcc programming that can be learned from the mechanism of Linux <img src = "// ir-jp.amazon-adsystem.com/e/ir?t=lespacetranqu-22&l=am2&o=" 9 & a = B075ST51Y5 "width =" 1 "height =" 1 "border =" 0 "alt =" "style =" border: none! Important; margin: 0px! Important; "/>

Try normal Linux programming Part 1 https://qiita.com/uturned0/items/b9ae846f2aff5865c074 Try normal Linux programming Part 2 https://qiita.com/uturned0/items/56beac990cdd6f1059ed Try normal Linux programming Part 3 https://qiita.com/uturned0/items/675092da8aa89c4b1ff0 Part 4 https://qiita.com/uturned0/items/8f5765cfc0f0be8a1981 Part 5 https://qiita.com/uturned0/items/ab97deb489c994a836da Part 6 https://qiita.com/uturned0/items/b7df48e87ae9170f3698 Part 7 https://qiita.com/uturned0/items/263151cf7c83bff7fac1


chapter 7

Make a head command

#include <stdio.h>
#include <stdlib.h>

static void do_head(FILE *f, long nlines);

int
main(int argc, char *argv[])
{
	if (argc != 2) {
	    fprintf(stderr, "Usage: %s n\n", argv[0]);
		exit(1);
	}
	do_head(stdin, atol(argv[1]));
	exit(0);
}

static void
do_head(FILE *f, long nlines)
{
	int c;

	if (nlines <= 0) return;
	while ((c=getc(f)) != EOF) {
		if (putchar(c) < 0) exit(1);
		if (c == '\n') {
		    nlines--;
    		if (nlines == 0) return;
		}
	}
}

execute

$ gcc -Wall head.c && cat head.c | ./a.out 2
#include <stdio.h>
#include <stdlib.h>

moved!

atol()

atol, atoll, atol_l, atoll_l -- convert ASCII string to long or long long integer long atol(const char *str);

Make the string a long number. What is a cast? I've tried

#include <stdio.h>
#include <stdlib.h>

int
main(int argc, char *argv[])
{
    char *str = "123";
    printf("%s \n",str);

    // printf("%d",str);    //This will result in an error

    //Because the return value is long%If it is not ld, an error will occur.
    printf("%ld \n", atol(str));

    //Try putting it in a long variable
    unsigned long n = atol(str);
    printf("%ld \n", n);

    //printf%d was an error, but you can put it in an int variable ...
    unsigned int i = atol(str);
    printf("%d \n", i);

}

execute

$ gcc -Wall atol.c && ./a.out 
123 
123 
123 
123 

It was casting. In the case of long, printf cannot be done unless it is set to % ld. Error if% d. But int n = can be done. Is there a scene where the compiler allows it?

I've never heard of % ld, but the compiler error is nice.

image.png

You know% ld without even going around. it's fantastic.

atoi() strtoll() strtol() strtod()

A system that casts characters to numbers

Why not use fgets ()

gets () is better because it doesn't have a buffer. Don't worry fgets () is not suitable due to line length restrictions

Omit number as n

nlines = number of lines

It seems to imitate the language Eiffel. Maybe it's C

Eiffel is a strongly typed (natural) object-oriented language designed by Bertrand Meyer. http://guppy.eng.kagawa-u.ac.jp/~kagawa/publication/eiffel.pdf

pass file as an argument

I forgot about it because I had a little time, but I remembered it. fopen ().

#include <stdio.h>
#include <stdlib.h>

static void do_head(FILE *f, long nlines);

int
main(int argc, char *argv[])
{
    long nlines;
    int i ;
	if (argc < 2) {
	    fprintf(stderr, "Usage: %s n\n", argv[0]);
		exit(1);
	}

    nlines = atol(argv[1]);

    if (argc == 2) {
		do_head(stdin, nlines);
    } else {
    	for (i=2; i<argc; i++) {
    	    FILE *f;
    	    f = fopen(argv[i], "r");
    	    if (!f) {
    	        perror(argv[i]);
    	        exit(1);
            }
            do_head(f, nlines);
            fclose(f);
    	}
    }
	exit(0);
}

static void
do_head(FILE *f, long nlines)
{
	int c;

	if (nlines <= 0) return;
	while ((c=getc(f)) != EOF) {
		if (putchar(c) < 0) exit(1);
		if (c == '\n') {
		    nlines--;
    		if (nlines == 0) return;
		}
	}
}


reulst

$ gcc -Wall head2.c && ./a.out 3 txt .git/config
abc
xyz

[core]
        repositoryformatversion = 0
        filemode = true

Single / double quotes get confused

It's an error if you set this to 'r' with single quote.

    	    f = fopen(argv[i], "r");

image.png

I thought it was single because it was one character, but ... I can type "rb", so it must be char type. maybe.

What are linux command options?

With or without parameters ls -a head -n 10

long option / short option head --line head -n

I've never said "let's make it a long option", so remember. Long option I like it.

It depends on the command whether = is required after the long option. Annoying place. The head doesn't matter.

head --line 5 head --line=5

- alone is" input from stdin " -- A single unit is used when you want to pass a character string starting with a minus as an argument, such as" Stop option analysis here. "

How.

I don't really understand -- because I don't use it much. The one I use the most is git checkout --index.html (revert the changed index.html). Maybe it's because there can be - in the filename that is the argument after-. Is that so. I wonder if I should have made a rule to parse like that. So that's it

getopt() Function for short option analysis. Sieve. From UNIX. It's amazing.

Ah. I've seen this in a bash script. After all. man has getopt (1) and getopt (3).

GETOPT (1) BSD General Commands Manual GETOPT(1) getopt -- parse command options GETOPT (3) BSD Library Functions Manual GETOPT(3) getopt -- get option character from command line argument list

You can decide the process for each option with while + switch case. I think I should remember it because it looks good, but I read it only roughly.

Movement is different with and without parameters For example, with head -n 5, the global variables that getopt has are as follows.

optopt = n //Note that the hyphen is gone
optarg = 5 //This is the parameter
optind = 2 //argv index

Well, it's just now, but is it a word definition that feels like option = parameter instead of key = value? The value is a parameter. Is that so.

Stop the analysis with - and-, but be careful because the location of optind changes for each of these two. - stays. -- moves to the next argument.

getopt_long(3)

 int
 getopt_long(int argc, char * const *argv, const char *optstring, const struct option *longopts, int *longindex);

You can also analyze long options! Oh ~~ the one I wanted to know. There is no command for this. It seems to be only in GNU libc.

Muu. Distracted and no good today. Sleeping YO

woke up. I'll do a little.

I didn't understand the word "member" to read more, so I learned

As with structs, class components are called members. There are member variables and member functions, but it is the same as writing ordinary variable declarations and function prototypes. Since it is declared here, there is no need to write a prototype declaration on the outside. https://cpp-lang.sevendays-study.com/day2.html#:~:text=%E3%83%A1%E3%83%B3%E3%83%90%E5%A4%89%E6%95%B0%E3%83%BB%E3%83%A1%E3%83%B3%E3%83%90%E9%96%A2%E6%95%B0,%E3%82%92%E6%9B%B8%E3%81%8F%E5%BF%85%E8%A6%81%E3%81%AF%E3%81%82%E3%82%8A%E3%81%BE%E3%81%9B%E3%82%93%E3%80%82

Let's do it with the feeling of class variables and class methods.

If you want to associate --help & -h with flags = NULL, val ='h', it seems like calling h of getopt (3) when --help comes. it's fantastic

The option that takes a boolean value (1 or 0) can be reflected in the variable as it is.

int opt_all = 0;

struct option[] = {
{"--all", no_argument, &opt_all, 1},

opt_all is the default zero, and when --all comes, opt_all should be set to 1. What is &?

Show the address of the & var variable itself https://qiita.com/pen2000/items/fc5b06795dce3e0f679c

It was a pointer. Maybe I declared it with * and used it with &. It's like putting 1 in the place where opt_all is. C-lang is hard ...

Head command with --lines and -n

#include <stdio.h>
#include <stdlib.h>
#define _GNU_SOURCE
#include <getopt.h>    //Read prototype declaration from GNU SOURCE

static void do_head(FILE *f, long nlines);

#define DEFAULT_N_LINES 10

static struct option longopts[] = {
    {"lines", required_argument, NULL, 'n'},
    {"help", no_argument, NULL, 'h'},
    {0, 0, 0, 0}   // <--------Marking that it is the last arrangement. Routine
};

int
main(int argc, char *argv[])
{
    int opt;
    long nlines = DEFAULT_N_LINES;

    while ((opt = getopt_long(argc, argv, "n:", longopts, NULL)) != -1) {
        switch (opt) {
            case 'n':
                nlines = atoi(optarg); //The number of lines comes in optarg
                break;
            case 'h':
                fprintf(stdout, "Usage: %s [-n LINES] [FILE ...]\n", argv[0]);
                exit(0);
            case '?':
                //Since this is error handling, it is similar to stderr. The content is getopt_long will give it to you!
                fprintf(stderr, "Usage: %s [-n LINES] [FILE ...]\n", argv[0]);
                exit(1);
        }
    }

    if (optind == argc) {
		do_head(stdin, nlines);
    } else {
        int i;

    	for (i=optind; i < argc; i++) {
    	    FILE *f;

    	    f = fopen(argv[i], "r");
    	    if (!f) {
    	        perror(argv[i]);
    	        exit(1);
            }
            do_head(f, nlines);
            fclose(f);
    	}
    }
	exit(0);
}

static void
do_head(FILE *f, long nlines)
{
	int c;

	if (nlines <= 0) return;
	while ((c=getc(f)) != EOF) {
		if (putchar(c) < 0) exit(1);
		if (c == '\n') {
		    nlines--;
    		if (nlines == 0) return;
		}
	}
}

result

@local:~/repos/futu$  gcc -Wall head3.c && ./a.out -n 3 txt
0a
1b
2c
@local:~/repos/futu$  gcc -Wall head3.c && ./a.out --lines 3 txt
0a
1b
2c
@local:~/repos/futu$ 

It moved.

What was an array {} instead of []?

What is this n:?

getopt_long(argc, argv, "n:", longopts, NULL)

const char * optdecl Is this an option decleration? List the options to analyze. If it is -a, -t, -x, you can use tax. For arguments that take parameters, add : at the end. If x requires value, then x:. When mixing with others, it doesn't matter what the order is, just the x and: stick together to form a lump. Like tax: or x: ta.

The option to use this time is ↓

Only shorttions are specified here. Then h and n: instead of n, because n takes a parameter. -n 10 for 10 lines. But the third argument is just n:, not hn:. I couldn't understand the reason for this. It says "Write only the short options you want to analyze", but what is analysis? Isn't switch case'h' an analysis? Unknown.

    if (optind == argc) {

At this point, optind (index of int argv array) has all defined options processed. The arguments that enter individually are ordinary arguments other than options. The a.txt and b.txt parts of head --lines 10 a.txt b.txt. The rest is processed by turning this argument.

Notes on using GPU libc

Probably using getopt () in getopt_long, it's pulling from the GNC libc. The C language works on any OS, but the one using GNC libc works only on Linux. There is no GNU windows If you use GNU libc, recognize that it can be used only on linux.

Use gdb! !! !! !! !!

Kita! !! !! I wanted to know! !! !!


I'm reading this book

<a target="_blank" href="https://www.amazon.co.jp/gp/product/4797328355/ref=as_li_tl?ie=UTF8&camp=247&creative=1211&creativeASIN=4797328355&linkCode=as2&tag=lespacetranqu-22&linkId=b690c3257ff896f2239f1107e > Normal Linux programming The royal road to gcc programming that you can learn from how Linux works <a target="_blank" href="https://www.amazon.co.jp/gp/product/B075ST51Y5/ref=as_li_tl?ie=UTF8&camp=247&creative=1211&creativeASIN=B075ST51Y5&linkCode=as2&tag=lespacetranqu-22&linkId=aa0915aa60a5a > Ordinary Linux programming 2nd edition: The royal road of gcc programming that can be learned from the mechanism of Linux

Recommended Posts

Try normal Linux programming Part 7
Try normal Linux programming Part 2
Try normal Linux programming Part 3
Try normal Linux programming Part 4
Try normal Linux programming Part 6
Trying normal Linux programming Part 1
Read Normal Linux Programming (Part 1 Only)
[For memo] Linux Part 2
Linux standard textbook part 5
New Linux commands! !! Part 2
Linux standard textbook part 4
Try NeosVR on Linux
Try programming with a shell!
Try GUI programming with Hy
Linux standard textbook memo 1 part 2
Reinforcement learning 5 Try programming CartPole?
Try translating English PDF Part 1
Try using SQLAlchemy + MySQL (Part 1)
Try using SQLAlchemy + MySQL (Part 2)
Making sound by programming Part 2
Linux standard textbook memo part 6
Try using Pillow on iPython (Part 1)
[For memo] Linux Part 1 vi editor
Try installing OpenAM on Amazon Linux
Try using Pillow on iPython (Part 2)
Try deep learning with TensorFlow Part 2
WSL2 ~ Linux on Windows ~ (Part 1: Introduction)
Try the Linux kernel lockdown mechanism
[Linux convenient command] Try inserting csview
Try using Pillow on iPython (Part 3)
[Linux convenient command] Try inserting bat
Story of trying competitive programming Part 1
Try compiling Linux commands (cross-compilation practice)