In the last post i wrote the basic cat command in C that could prints the content of the files to the standard output. Now it is time to update it, adding two features.
- Using the program as cat without any command line arguments
- Using -n option to print line numbers
For the first part, these are the changes made to original program (Please read the previous blog).
#define MAX 1000
int main(int argc, char *argv[])
{
char input[MAX];
else
{
while (1)
{
scanf("%s", input);
printf("%s\n", input);
}
}
Here the input is an array of type char. If the argc is 0 then it comes under else block and then to the while loop, where for each iteration the input is read from standard input and prints it to standard output.
For the second part, a new function is created printFile().
#define TRUE 1
#define FALSE 0
void printFile(char *argv[], int argc, int index, int numbers)
{
char character;
int count = 0;
for (int i = index; i < argc; i++)
{
FILE *file = fopen(argv[i], "r");
if (numbers)
printf("\t%d ", ++count);
while ((character = fgetc(file)) != EOF)
{
printf("%c", character);
if (numbers && character == '\n')
printf("\t%d ", ++count);
}
fclose(file);
}
}
Here the signature of the function is,
void printFile(char *argv[], int argc, int index, int numbers);
Here the index is from where the loop starts, and numbers takes value of 1 and 0, if it is 1 it prints the numbers or else it doesnβt.
if (argc > 1)
{
if (strcmp(argv[1], "-n") == 0)
{
printFile(argv, argc, 2, TRUE);
}
else
{
printFile(argv, argc, 1, FALSE);
}
}
Here checking if first argument is β-nβ, if it is then calling printFile() with argv, argc, index = 2, and numbers = TRUE or else it is calling printFile() with argv, argc, index = 1, and numbers = FALSE.
#include <stdio.h>
#include <string.h>
#define MAX 1000
#define TRUE 1
#define FALSE 0
void printFile(char *argv[], int argc, int index, int numbers)
{
char character;
int count = 0;
for (int i = index; i < argc; i++)
{
FILE *file = fopen(argv[i], "r");
if (numbers)
printf("\t%d ", ++count);
while ((character = fgetc(file)) != EOF)
{
printf("%c", character);
if (numbers && character == '\n')
printf("\t%d ", ++count);
}
fclose(file);
}
}
int main(int argc, char *argv[])
{
char input[MAX];
if (argc > 1)
{
if (strcmp(argv[1], "-n") == 0)
{
printFile(argv, argc, 2, TRUE);
}
else
{
printFile(argv, argc, 1, FALSE);
}
}
else
{
while (1)
{
scanf("%s", input);
printf("%s\n", input);
}
}
return 0;
}
Checkout the repository at GitHub.
Top comments (0)