Search code examples
cscanffwrite

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>
#define MAX_LEN 30


int main(int argc, char * argv[]){

  FILE *ifp;
  FILE *ofp;

  if(argc != 4){
    fprintf(stderr, "Usage: flag %s 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", 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");

  unsigned char tempstr[MAX_LEN];
  unsigned int tempint;

  while(fscanf(ifp, "%u     %u\n",(unsigned int*)&tempstr, &tempint) == 2){

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

  }

  fclose(ifp);


  return 0;
}

When I run my code my while loop does not seem to be running(ie.the "ran loop" is not being output). Not sure where to go from here?

Also my calls at the command line are as follows:

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

Any help would be appreciated! Thanks!


Solution

  • I believe this should get rid of the seg fault.

    1. The type should be char * instead of unsigned char *
    2. The array should have enough space to hold the required characters plus the null terminator.

    .

    char tempstr[30];
    unsigned int tempint;
    
    while (fscanf(ifp, "%s \t %i\n",tempstr, &tempint) == 2 ) {
        fwrite((const void*)&tempstr, sizeof(tempstr)+1, 1, ofp);
        fwrite((const void*)&tempint, sizeof(unsigned int), 1, ofp);
        puts("ran loop");
    }
    

    Also I guess you don't need main.c, while executing ./a.out ... etc. You can change check for argc != 3 instead of 4 in your code.