0

Read numbers from an input file. Then sort them using any sorting algorithm. Then finally print the sorted numbers in another text file. I have tried the following code but it is not showing the output in another file.

#include "s.h";

#include<stdio.h>

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

{

    int *a,num,i;

    FILE *fp,*ft;

    char s[5];

    fp=fopen("input.txt","r");

    sscanf(argv[1],"%d",&num);

    printf("%d\n",num);

    a=(int *)malloc(num*sizeof(int));

    for(i=0;i<num;i++)

    {

        fgets(s,10,fp);

        sscanf(s,"%d",a+i);

    }

    selection(a,num);

    fclose(fp);

    free(a);

    ft=fopen("output.txt","w");

    for(i=0;i<num;i++)

    {

        fprintf(ft,"%d",*(a+i));

        fputs(s,ft);

        fputs("\n",ft);

    }

    fclose(ft);

    return 0;

}
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70
kunal51
  • 11
  • 4

2 Answers2

1

There can be multiple reasons for segmentation fault, but most importantly,

  1. In your code, first you're calling free(a); and then you're trying to access the free-d memory by fprintf(ft,"%d",*(a+i));. Put the free(a); before return 0; statement.

  2. You're not checking for the success of fopen()s. If fopen() fails, then you'll be end up accessing NULL pointers.

  3. You're not performing a NULL check of argv[1].

  4. you're trying to copy 10 elements [if available] to a buffer having the space for only 5. change fgets(s,10,fp); to fgets(s,5,fp);

  5. Do not forget to #include <stdlib.h> for malloc(). Also, put a check for success/failure of malloc().

Note: Please do not cast the return value of malloc().

Also, we don't know what is happenning inside selection(a,num);

Community
  • 1
  • 1
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • assuming you're on linux, can you compile your code with `-g`flag, then run use `gdb` and tell us the location of segmentation fault? – Sourav Ghosh Dec 08 '14 at 14:34
1

You are freeing a before writing it to output.txt !

The end of your program should be :

    ...
    fclose(fp);
    /* free(a); too early, still need to be written */
    ft=fopen("output.txt","w");
    for(i=0;i<num;i++)
    {
        fprintf(ft,"%d",*(a+i));
        fputs(s,ft);
        fputs("\n",ft);
    }
    fclose(ft);
    free(a);
    return 0;
}

But you should also :

  • test the result of both fopen
  • test the result of all scanf
  • test the result of fgets

The rule is : always control what you did not produce yourself

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
  • still not getting the answer. – kunal51 Dec 08 '14 at 14:30
  • @kunal51: It works in my tests - even if the output is ugly (what means the `fputs(s, ft)` ?) and if I had to comment out the `selection(a)` call (where is the source ?). If you need more help, show `input.txt`, the source for `selection` and how you call your program. – Serge Ballesta Dec 08 '14 at 15:09