View Single Post
Old 08-04-2006, 06:14 PM   #5 (permalink)
cn880
Registered User
 
Join Date: Aug 2006
Posts: 5
cn880 is on a distinguished road
It took a bit more thinking, but it finally works properly. Thank you so much for all of your help.

Here is my completed code:

Code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

/* predefine the file-creation function so that we know it exists when
   referencing from main() */

int create_file (char* filename, int count);

int main (int argc, char** argv)
{
	char opt;			/* this will hold the return value
					   from optind */

	int count = 1;			/* create one file by default */
	int j;
        int i;

	while ((opt = (char) getopt (argc, argv, "n:h")) > 0)
	{
		switch (opt)
		{
					/* copies of filename created */
			case 'n':	count = atoi (optarg);
					break;

					/* help message */
			case 'h':	printf("Usage: %s [-n ", argv[0]);
					printf("<count>] [filename1[ ...]]\n");
					return 0;
		}
	}

	/* ``at this point the provided optind from getopt() will point
	   somewhere in argv[], we need to cover every position it might
	   have'' */

					/* normally, it should point from the
					   beginning. */

	if (optind == 3)
	{
					/* assume remaining arguments
					   indicate which filename to use. */
		for (i = optind; i < argc; ++i)
				create_file(argv[i], count);
	}

	else
		if (optind == argc || optind > argc)
		{
					/* was given as last arg in this case */
			for (i = 1; i < (argc -2); ++i)
					create_file(argv[i], count);
		}

		else { 
			if (optind == argc && optind < argc) {
					/* it was given in the middle! */
			for (i = 1; i < (argc -2); ++i)
					create_file(argv[i], count);
			}


			else
			{
					/* was only called with filename */
				for (i = 1; i < argc; ++i)
						create_file(argv[i], count);
			}
		}

	return 0;
}

int create_file (char* filename, int count) {
	char* buff;			/* our filename with dynamic memory 
					   allocation */

					/* how long `char*' will need to be; + 3
					   to add room for `-' and `\0' */
	int length = strlen (filename) + 3;
	int i;
	int n = count;
	
	while (n >= 10) {		/* decide length */
		length++;
		n = n / 10;
	}

					/* allocate memory for filename-x */
	if (!(buff = (char*) malloc (sizeof (char*) * length)))
		return -1;		/* error allocating */

	for (i = 1; i <= count; ++i) {
		snprintf (buff, length, "%s-%d", filename, i);

		if (!access (buff, F_OK))
			printf ("%s: File exists\n", buff);

		else {
			FILE *success = fopen  (buff, "w");

			if (!success)
				printf ("%s: Error creating file.", buff);
			else
				printf ("Created file: %s\n", buff);
		}
	}

	free (buff);			/* free memory */

	return 0;
}
Thanks again. I'm new at this, so there may be some conventions I am breaking. You can point those out if you'd like.
cn880 is offline   Reply With Quote