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;
}
There can be multiple reasons for segmentation fault, but most importantly,
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.
You're not checking for the success of fopen()
s. If fopen()
fails, then you'll be end up accessing NULL
pointers.
You're not performing a NULL
check of argv[1]
.
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);
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);
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 :
fopen
scanf
fgets
The rule is : always control what you did not produce yourself
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.