Reputation: 131
My program check if two files (with a different path / name) match or not. The hard and symbolic links between the files are followed to determine it.
How can I modify the program to see what happens if the files I want to compare are device files? Or directories? Both seem valid uses. Also checking the device
#include <unistd.h>
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
void printUsage()
{
printf("Use: ./leg <name_file1> <name_file2>.\n");
}
int createStat(const char *file, struct stat *fileStat)
{
if (stat(file, fileStat) < 0)
{
fprintf(stderr,"Error! File %s does not exist.\n", file);
return 0;
}
return 1;
}
int main(int argc, char **argv)
{
if (argc < 3)
{
printf("Insufficient number of parameters.\n");
printUsage();
return -1;
}
struct stat fileStat1;
struct stat fileStat2;
if (createStat(argv[1], &fileStat1) == 0)
{
return -1;
}
if (createStat(argv[2], &fileStat2) == 0)
{
return -1;
}
if (S_ISREG(fileStat1.st_mode) && S_ISREG(fileStat2.st_mode)) {
if ((fileStat1.st_dev == fileStat2.st_dev) && (fileStat1.st_ino == fileStat2.st_ino)) {
printf("Files '%s' and '%s' coincide.\n", argv[1], argv[2]);
} else
printf("Files '%s' and '%s' do not match.\n", argv[1], argv[2]);
} else
fprintf(stderr,"'%s' and '%s' there are no files.\n", argv[1], argv[2]);
return 0;
}
Upvotes: 0
Views: 122
Reputation: 144550
For regular files and directories, comparing the st_dev
and st_ino
fields is sufficient.
For paths representing character or block devices, comparing the st_dev
and st_ino
fields will tell you if they are the same file, ie: different paths to the same directory entry, including symbolic link indirections. Comparing the st_rdev
fields will tell if they represent the same device, which is also useful but a different thing.
Also note that fprintf(stderr,"Error! File %s does not exist.\n", file);
may produce a misleading message: access
failure may be caused by other reasons. It is simple and efficient to produce the correct message this way:
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
int createStat(const char *file, struct stat *fileStat) {
if (stat(file, fileStat) < 0) {
fprintf(stderr, "Cannot stat file %s: %s\n", file, strerror(errno));
return 0;
}
return 1;
}
Upvotes: 2