I'm having trouble with this program, it's working perfectly when I use stdin but when I modify it to get characters from the command line it doesn't. I know I'm doing something wrong but don't know what, any help would be greatly appreciated.
Description and code:
/* Program prints the date in this form: September 13, 2010
allow the user to enter date in either 9-13-2010 or 9/13/2010
format, otherwise print 'error' */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *month(int m)
{
char *months[]={"January","February","March","April","May",
"June", "July","August","September","October",
"November","December"};
return months[m-1];
}
int main(int argc, char *argv[])
{
int m=0,d=0,y=0;
FILE *fp;
if((fp=fopen(argv[1],"rb")) == NULL)
{
fprintf(stderr,"Couldn't open the file. ");
exit(EXIT_FAILURE);
}
printf("Type a date (mm-dd-yyyy) or (mm/dd/yyyy): \n");
if(fscanf(fp,"%d%*[/-]%d%*[/-]%d",&m,&d,&y) != 3) //store characters in variables
{
fprintf(stderr, "Not properly formatted.");
exit(EXIT_FAILURE);
}
printf("%s %2d, %4d",month(m),d,y);
return 0;
}
Input:
01/30/1990
Output:
Couldn't open the file.
fopen("01/30/1999","rb")will try to open a file with the path01/30/1999. Obviously, no such file exists.argv[1]has undefined behaviour unless you previously ascertain thatargcis at least two.fscanf(file-scanf) onfp, but usesscanf(string-scanf) onargv[1].fprintf(stderr,"Couldn't open the file. ");(which produces a nearly useless error message), tryperror( argv[1]), which will tell you exactly what the problem is.