Hello all,
I tried using 'getopt' for my program(sorting) ...but always end up with a Segmentation Fault..
input suppose to be as follows:
./msort -i 'input file' -o 'output file' -s 'sort type' -f 'field to be sorted'
This is a part of my main.
right now, i skip the write to file part and just print it to 'stdout'Code:while((c = getopt(argc, argv, "iosf:")) > 0)
{
switch(c)
{
case 'i':
if(sscanf(optarg, "%s", file_in) != 1)
fprintf(stderr,"Input file was not provided\n");
break;
case 'o':
if(sscanf(optarg, "%s", file_out) != 1)
fprintf(stderr,"Output file was not provided\n");
break;
case 's':
if(sscanf(optarg, "%c", &sort_type) != 1)
fprintf(stderr,"Sort type not provided\n");
break;
case 'f':
if(sscanf(optarg, "%d", &field) != 1)
fprintf(stderr,"Field to be sorted not provided\n");
if(field == 2)
printf("String field selected to be sorted\n");
else
printf("Record Number field selected to be sorted\n");
break;
}
}
fp1 = fopen(file_in,"r");
if(fp1 == NULL) perror("Cannot open file for reading\n");
rec_count = read_records(records, fp1);
printf("%d records read from input file\n", rec_count);
records = realloc(records, (sizeof(records)*(rec_count+4)));
/*Sorting starts here*/
/*Not yet complete, but default is present already*/
if((sort_type == 'n') && (field == 2))
{
/*sort with natural mergesort - string*/
printf("Natural Mergesort selected\n");
}
else
if((sort_type = 'n') && (field == 1))
{
/*sort with natural mergesort - int*/
printf("Natural Mergesort selected\n");
}
else
if((sort_type = 'b') && (field == 2))
{
/*sort with BU mergesort - string*/
printf("Bottom-Up Mergesort selected\n");
mergesortBU(records, 0, rec_count-1, comp_string);
}
else
{
/*sort with BU mergesort - int*/
printf("Bottom-Up Mergesort selected\n");
mergesortBU(records, 0, rec_count-1, comp_key_num);
}
If I use this,
file_in = argv[1]
to test my sorting and output, it works fine.
But doesn't seem to be working with getopt.
Help.
Thx.