jeudi 26 février 2015

Converting strings and ints from input file and printing to output file

I am trying to convert strings and integers to binary using fscanf and fwrite to write them to an output file.


My input file:



a 100
ab 99
abc 98
abcd 97
abcde 96


Each space separating the string and int on each line is a tab.


Here is my main.c file where the magic should be happening (but is not):



#include <stdio.h>
#include <stdlib.h>
int main(int argc, char * argv[]){

FILE *ifp;
FILE *ofp;
long pos;

if(argc != 4){
fprintf(stderr, "Usage: flag program input-file output-file\n", argv[0]); exit(1);
}

if((ifp = fopen(argv[2], "r")) == NULL){ /* error check to make sure the input file is open*/
fprintf(stderr, "Could not open file: %s\n", argv[2]); exit(1);
}

puts("input file open\n");

if((ofp = fopen(argv[3], "wb")) == NULL){ /* Opens output file to write in binary*/
puts("couldnt open output file\n"); exit(1);
}

puts("output file open\n");
pos = ftell(ifp);

unsigned char tempstr[sizeof(unsigned char)];
unsigned int tempint;
int i;

while(fscanf(ifp, "%s\t%i\n", &tempstr, &tempint) == 2){

fwrite((const void*)tempstr, sizeof(unsigned char), 1, ofp);
fwrite((const void*)tempint, sizeof(unsigned int), 1, ofp);
puts("ran loop");

}

fclose(ifp);


return 0;
}


When I run my main I get a SegFault as the while loop starts. I'm not sure what is going wrong here, I have used scanf to read from a file before (with the scanf call in the while test parameter. But for some reason this isn't working. Could it be my fwrite calls?


Also my calls at the command line are as follows:


./a.out main.c t1.txt t1.bin


Any help would be appreciated! Thanks!


Aucun commentaire:

Enregistrer un commentaire