Linux Programming – Part 14.1: Improved Version of Cat Command

The improved version of the cat command.

Here’s another example of the cat command, but this time it’s improved!!

Here’s an improved version of the previous cat command that I shared with you. As I mentioned earlier, my enthusiasm for Linux is unstoppable, and I enjoy exploring the open-source world using the legacy but robust C language!

Here’s another code!!

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

static void do_cat(char* file)
{
    FILE *f;
    int c;

    f = fopen(file, "r");
    if (!f)
    {
        perror(file);
        exit(1);
    }
    while ((c = fgetc(f)) != EOF)
    {
        if (putchar(c) < 0)
            exit(1);
    }
    fclose(f);
}

static void do_write(char* input_file, char* output_file)
{
    FILE *f1;
    FILE *f2;

    f1 = fopen(input_file, "r");
    if (!f1)
    {
        perror(input_file);
        exit(1);
    }

    f2 = fopen(output_file, "w+");
    if (!f2)
    {
        perror(output_file);
        exit(1);
    }

    int count;
    char buffer[1024];

    while ((count = fread(buffer, 1, sizeof(buffer), f1)) != 0)
    {
        fwrite(buffer, 1, count, f2);
    }
    fclose(f1);
    fclose(f2);
}


int main(int argc, char *argv[])
{
    int i;

    if (argc < 3)
    {
        fprintf(stderr, "%s: Please select two files here\n", argv[0]);
        exit(1);
    }

    // read
    for (i = 1; i < argc - 1; i++)
    {
        do_cat(argv[i]);
    }

    // write
    do_write(argv[argc - 2], argv[argc - 1]);

    return 0;
}

Description:

This C program takes two file names as command line arguments and performs two operations on them. First, it reads the content of each file using the do_cat function and displays it on the console. Second, it copies the content of the first file into the second file using the do_write function.

The do_cat function takes a filename as a parameter and opens the file in read mode. It then reads the file character by character using a while loop and displays each character on the console using the putchar function.

The do_write function takes two filenames as parameters and opens the input file in read mode and the output file in write mode. It then reads the content of the input file using a while loop and a buffer of 1024 bytes. It writes the content of the buffer into the output file using the fwrite function. The function continues to read and write the input file until it reaches the end of the file. Finally, it closes both files using the fclose function.

In the main function, the program first checks if there are at least three command line arguments. If there are not, it displays an error message and exits the program. Otherwise, it calls the do_cat function for all files except the last two and then calls the do_write function for the last two files.

Leave a Reply