View Single Post
Old 08-03-2006, 09:55 PM   #1 (permalink)
cn880
Registered User
 
Join Date: Aug 2006
Posts: 5
cn880 is on a distinguished road
C: Help me with a file generation program?

I began learning C about one day ago. So far, I have successfully written a program that removes files (or notifies you if you attempt to remove a file that does not exist).

I was not so lucky with my second program, however. What it mainly does is create files of a certain name. My difficulties began I tried to add an option to create a certain number of files of similar names. What I would like it to do is behave so that if the command

Code:
$ ./ifc -n 3 newfile otherfile
were issued, the following files would be created:

Code:
$ ls

newfile-1 newfile-2 newfile-3 otherfile-1 otherfile-2 otherfile-3
In reality, however, this is all that happens:

Code:
$ ./ifc -n 3 newfile

$ ls

newfile-1
gcc has no problems compiling my program. Here is the specific code block I am having trouble with:

Code:
/* This `for' loop processes each filename. */

for (i = 3; i < argc; i++) /* to skip `./ifc', `-n' and `3' cmd line args */
{                               
	int j; /* j keeps track of how many files of each filename are created */

	/* This `for' loop processes each individual file. */

	for (j = 1; j <= n; j++) /* `n' is 3, because of `-n 3' args */
	{
		char jstr[50]; /* jstr holds the whole name of the file */

		sprintf (jstr, "%s-%d", argv[i], j); /* use sprintf store the name */

		FILE *file = fopen (jstr, "r"); /* make sure the file doesn't exist */

		/* if fopen can find the file... */

		if (file != 0) /* stop if the file is found */
		{
			printf ("\n%s: File exists.\n", jstr);
			fclose (file);
		}

		else /* We're okay for creation. */
		{
			fclose (file);
			FILE *success = fopen (jstr, "w"); /* create the file */

			if (success == 0) /* in case it ends up not working */
			{
				printf ("\n%s: ", jstr);
				printf ("Creation unsuccessful.\n");
			}
		}
	}
}
Thank you in advance for any assistance you may be able to give.
cn880 is offline   Reply With Quote