cat/Cat.c
2023-03-30 22:02:58 -05:00

121 lines
2.9 KiB
C
Executable File

#include <stdio.h>
#include <stdbool.h>
bool CheckArgumentSet(int argc, char* argv[]);
void EchoBox();
void FileHandler(int argc, char* argv[]);
bool IsFileReadable(FILE* currentFile, char* fileName);
void PrintChosenFile(FILE* currentFile);
void PrintChosenFileNumbered(FILE* currentFile);
int lineNumber = 1;
int main(int argc, char* argv[])
{
if (argc == 1)
EchoBox();
if (argc > 1)
FileHandler(argc, argv);
return 0;
}
// Check if line number argument is set
bool CheckArgumentSet(int argc, char* argv[])
{
char argumentHyphen = '-';
char argumentLetter = 'b';
for (int i = 1; i < argc; i++)
{
if ((*(argv[i]) == argumentHyphen) && (*(argv[i]+1) == argumentLetter))
{
return 1;
}
}
return 0;
}
// Handling Cat without arguments
void EchoBox()
{
char inputText[100];
while (true)
{
scanf("%s", inputText);
printf("%s\n", inputText);
}
}
// Base function for passing work to other functions
void FileHandler(int argc, char* argv[])
{
FILE* currentFile;
bool argumentEnabled = CheckArgumentSet(argc, argv);
for (int i = 1; i < argc; i++)
{
if ((currentFile = fopen(argv[i], "r")) == NULL)
{
if (!argumentEnabled)
fprintf(stderr, "cat: %s: No such file or directory\n", argv[i]);
continue;
}
if (argumentEnabled)
PrintChosenFileNumbered(currentFile);
if (!argumentEnabled)
PrintChosenFile(currentFile);
fclose(currentFile);
}
}
// Print text of a chosen file without line numbers
void PrintChosenFile(FILE* currentFile)
{
char buffer[4];
while (fgets(buffer, sizeof(buffer), currentFile))
{
printf("%s", buffer);
}
}
// Print text of a chosen file with line numbers
void PrintChosenFileNumbered(FILE* currentFile)
{
bool isNewLine = 0;
char buffer[2];
printf(" %2d ", lineNumber);
lineNumber = lineNumber + 1;
while (fgets(buffer, sizeof(buffer), currentFile))
{
if (isNewLine && (buffer[0] == '\n'))
{
printf("%s", buffer);
continue;
}
if (isNewLine && (buffer[0] != '\n'))
{
printf(" %2d %s", lineNumber, buffer);
lineNumber = lineNumber + 1;
isNewLine = 0;
continue;
}
if (!isNewLine && (buffer[0] == '\n'))
{
isNewLine = 1;
printf("%s", buffer);
continue;
}
printf("%s", buffer);
}
}
// Check if file is readable
// Return true if readable, and false if not readable
// Todo: Fix function, breaks code if used
bool IsFileReadable(FILE* currentFile, char* fileName)
{
if((currentFile = fopen(fileName, "r")) == NULL)
{
fprintf(stderr, "cat: %s: No such file or directory\n", fileName);
return 0;
}
return 1;
}