I am trying to make my own cat command in C by the name of "lolcat". It will read the command line arguments such as file name, open that file and print its contents in reverse order. The program is working fine when I run such commands as :
./lolcat file1.txt It prints the file content in reversed order.
But when I try to implement the -n functionality to count the total number of lines. such as ./lolcat -n file1.txt It displays segmentation fault(core dumped).
I have the attached the code below:
#include <stdio.h>
int main(int argc , char *argv[])
{
printf("%s" , argv[1]);
int command = 0;
if(argv[1] == "-n")
{
command = 2;
}
else{
command = 1;
}
for(int i = command ; i < argc ; i++)
{
FILE *myFile = NULL;
myFile = fopen(argv[i] , "r");
char word[255];
char c;
int c_count = 0;
int w_count = 0;
int l_count = 0;
int prev_c_count = 0;
int x = 0;
int out = 0;
while((c = fgetc(myFile)) != EOF)
{
word[x] = c;
c_count++;
if(c == '\n' || c == '\0')
{
l_count++;
if(command == 1)
{
for(int j = c_count - 1 ; j>=prev_c_count ; j--)
{
printf("%c" , word[j]);
}
}
prev_c_count = c_count;
}
x++;
}
printf("\n");
l_count++;
if(command == 1)
{
for(int j = c_count - 1 ; j>=prev_c_count ; j--)
{
printf("%c" , word[j]);
}
}
prev_c_count = c_count;
printf("\n");
}
return 0;
}
if(argv[1] == "-n")is NOT how you compare C strings... Trystrcmp()... So, the program tries to open a file named "-n", fails, and the code continues to suck on that dry pipe... What do you expect the system to do when you don't check return codes from system calls like fopen()?argv[1] == "-n"is not a defined way to do string comparison in c. Your compiler should be warning you about that.