Two mistakes in your program:
- You included the prototype for the is_symlink() function in main(), but you didn't call it at all. So the is_symlink() never runs, leaving the only thing the program does to just read the file from user-input, without doing anything further. Just add a line "is_symlink(filename);" at the end of main() to fix this.
- You call stat() to check if the entered file is a symlilnk. But stat() will follow the link and report information about the file a symlink points to. So stat() will never tell it's a symlink. For this purpose you need to use lstat(). (see the man page for stat, fstat, lstat)
Two other remarks:
If you would also print a message saying it's not a symlink, you would have noticed the is_symlink() function never executes. Even if that's not what you want, it makes sense when first trying to run/debug your program.
Using scanf() on a string of max 99 characters (plus the terminating '\0' character makes 100) is "dangerous". If the user enters more that a 100 characters, scanf() writes beyond the buffer (buffer-overflow bug), and your program will most probably crash with a segmentation fault. If not it will have a security bug at least.
Here's a changede version of your prograam with all 4 issues mentioned above fixed.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#define MAXFILENAMELEN 100
/* Prototype for function */
void is_symlink(const char *filename);
int main()
{
int len;
char filename[MAXFILENAMELEN];
printf("Enter a file name: ");
fgets(filename, MAXFILENAMELEN, stdin);
/* Remove the newline from the end if it' there */
len = strlen(filename);
if (filename[len-1] == '\n') {
filename[len-1] = '\0';
}
/* Call function to test if it is a symlink */
is_symlink(filename);
return 0;
}
void is_symlink(const char *filename)
{
struct stat p_statbuf;
if (lstat(filename, &p_statbuf) < 0) { /* if error occured */
perror("calling stat()");
exit(1); /* end progam here */
}
if (S_ISLNK(p_statbuf.st_mode) == 1) {
printf("%s is a symbolic link\n", filename);
} else {
printf("%s is NOT a symbolic link\n", filename);
}
}