cis-452-lab-12/programming-assignment.c

124 lines
3.1 KiB
C

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
/**************************************************************************
* Authors: Gary Fleming, Amber McCloughan
* Class: CIS452 - Operating Systems Concepts
* Professor: Dr. Greg Wolffe
* Date: 4/19/2019
*
* Program that mimics the ln command's basic functionality.
* You can create soft links or hard links using this program.
*
* Arguments
* -------------------------------------------------------------------------
* -s : Specifies we're creating a soft link.
* [source] : Input a file that will be linked to. MUST COME
* FIRST!
* [destination] : Input a file name for the new link file. MUST
* COME LAST!
***************************************************************************/
#define MAX_BUF_SIZE 102
/**
* Main function of the program. Takes in
* three possible arguments: -s, [source],
* and [destination].
*
* @param argc, number of arguments.
* @param argv, the actual arguments.
*/
int main(int argc, char *argv[])
{
// Tracking if we're doing a symlink.
int sFlag = 0;
// For counting arguments.
int numCount = 0;
// Used in the for loop when checking arguments.
int i;
// Buffer for link source.
char *source = malloc(MAX_BUF_SIZE * sizeof(char));
// Buffer for the new link.
char *dest = malloc(MAX_BUF_SIZE * sizeof(char));
// Reading the program arguments.
for (i = 1; i < argc; i++)
{
// If we found the -s flag.
if (!strcmp(argv[i], "-s"))
{
sFlag = 1;
}
// For file path arguments.
else
{
// For the source file.
if (numCount == 0)
{
strcpy(source, argv[i]);
numCount++;
}
// For the destination file (link).
else if (numCount == 1)
{
strcpy(dest, argv[i]);
numCount++;
}
// There must have been too many arguments.
else
{
printf("Too many arguments provided!\n");
free(source);
free(dest);
return -1;
}
}
}
// There must have not been enough arguments.
if (numCount < 2)
{
printf("Not enough arguments provided!\n");
free(source);
free(dest);
return -1;
}
// If we're dealing with a hard link.
if (sFlag == 0)
{
if (link(source, dest) < 0)
{
perror("Huh? There is... ");
free(source);
free(dest);
return -1;
}
}
// Otherwise, we're dealing with a soft link.
else
{
if (symlink(source, dest) < 0)
{
perror("Huh? There is... ");
free(source);
free(dest);
return -1;
}
}
// Freeing resources.
free(source);
free(dest);
// Goodbye (for the semester)!
return 0;
}