This is a read and writing the binary data to and from a file program. The program has to take command line arguments to specify the input and output files to use.
This means that I have several valid ways to invoke the program. Argument order should not matter.
./binaryio -i input.dat -o output.dat
./binaryio -o output.dat -i input.dat
./binaryio -i foo.dat -o foo.dat
my binary file im reading from is "pewp.dat" (sorry about the immature file name, i am a little immature at times)
When i run my program this way "./binaryio -i pewp.dat -o output.dat" it runs without any errors and creates my output.dat file and writes what was in my pewp.dat file.
but when i "./binaryio -o output.dat -i input.dat" i get a seg fault, not really sure why its giving me that maybe someone can help me.
here is the codez
Code:
#include <stdio.h>
#include <stdlib.h>
void sort(int arr[], int *num_items);
int main(int argc, char * argv[])
{
int cap = 10;
int *arr = malloc( cap * sizeof(int));
int i, num_items;
FILE * fptr;
for(i=1; i < argc; ++i)
{
if(strcmp(argv[i], "-i"))
{
fptr = fopen(argv[i], "r");
num_items = fread ( arr, sizeof( int ), cap, fptr );
printf( "number of items read = %d\n", num_items );
sort( arr, &num_items );
for( i=0; i<num_items; ++i)
{
printf("%d ", arr[i]);
}
printf("\n");
fclose( fptr );
}
if(strcmp(argv[i], "-o"))
{
fptr = fopen(argv[i], "w");
fwrite ( arr, sizeof( int ), cap , fptr );
fclose( fptr );
}
}
return 0;
}