Bill Cunningham said:
I have this code I would like to clean up.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
double x, y, a, b;
FILE *fp;
x = strtod(argv[1], NULL);
y = strtod(argv[2], NULL);
a = strtod(argv[3], NULL);
b = strtod(argv[4], NULL);
if ((fp = fopen(argv[4], "a")) == NULL) {
puts("fopen error");
exit(-1);
}
fprintf(fp, "%.2f\t%.2f\t%.2f\t%.2f\n", x, y, a, b);
if (fclose(fp) == EOF) {
puts("fclose error");
exit(-1);
}
return 0;
}
If the program is run with no arguments I get a seg fault. If it is run
with 4, no problem. If it is run with less than four (that includes
argv[0]) then the program doesn't want to run right. How would I be able
to use this program with say one or two argvs ?
#include <stdio.h>
#include <stdlib.h>
#define DEFAULT_FILE_NAME "foo.bar"
int main(int argc, char *argv[])
{
double x = 0.0, y = 0.0, a = 0.0, b = 0.0;
const char *filename = DEFAULT_FILE_NAME;
FILE *fp = NULL;
if(argc > 1)
{
x = strtod(argv[1], NULL);
}
if(argc > 2)
{
y = strtod(argv[2], NULL);
}
if(argc > 3)
{
a = strtod(argv[3], NULL);
}
if(argc > 4)
{
b = strtod(argv[4], NULL);
filename = argv[4];
}
if ((fp = fopen(filename, "a")) == NULL) {
puts("fopen error");
exit(EXIT_FAILURE);
}
fprintf(fp, "%.2f\t%.2f\t%.2f\t%.2f\n", x, y, a, b);
if (fclose(fp) == EOF) {
puts("fclose error");
exit(EXIT_FAILURE);
}
return 0;
}