
Originally Posted by
john.c
Your "err" routine is pointless.
I made it a function to avoid redundancy, because I might use the same error message in the future.

Originally Posted by
john.c
And you need to check argc before accessing argv[1].
Thanks for telling me, I didn't notice it.

Originally Posted by
john.c
\e is a non-standard escape sequence. Better to use \033 or \x1b.
I'll make sure to fix that too. What is the difference between these three escape sequences?
Also, thanks for the example code.
EDIT:
Here is my updated code:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#define ERRMSG "\033[1;91mError:\033[0m "
#define USAGE "\nUsage: thing [filename]"
int err(unsigned char message, char args[])
{
if(message == 0)
{
printf("%stoo few arguments%s", ERRMSG, USAGE);
}
if(message == 1)
{
printf("%stoo many arguments%s", ERRMSG, USAGE);
}
if(message == 2)
{
printf("%sfile \"%s\" not found", ERRMSG, &args[0]);
}
if(message == 3)
{
printf("%s\"%s\" is a directory", ERRMSG, &args[0]);
}
if(message == 4)
{
printf("%s\"%s\" is not a normal file", ERRMSG, &args[0]);
}
puts("");
exit(EXIT_FAILURE);
}
int main(int argc, char* argv[])
{
FILE *fptr;
if(argc < 2)
{
err(0, NULL);
}
else if(argc > 2)
{
err(1, NULL);
}
fptr = fopen(argv[1], "r");
if(fptr == NULL)
{
err(2, argv[1]);
}
struct stat st;
fstat(fileno(fptr), &st);
if ((st.st_mode & S_IFMT) == S_IFDIR)
{
err(3, argv[1]);
}
if ((st.st_mode & S_IFMT) != S_IFREG)
{
err(4, argv[1]);
}
fclose(fptr);
return 0;
}
I am still using the err function for the reasons stated above.