I'am having some problems with files. I try to write the sorted array to the file but it just fills it with trash.
My understanding is that i open a new file called Inteiros2.txt and it fwriting writes the numbers. But that's clearly not the case, what's rong?
Code:
#include <stdio.h>
void SelectionSort(int v[], int n)
{
for(int i=0;i<n-1;i++)
{
int iMin=i;
for(int j=i+1;j<n;j++)
{
if(v[j]<v[iMin])
iMin=j;
}
int aux=v[i];
v[i]=v[iMin];
v[iMin]=aux;
}
}
int main()
{
FILE *f;
f=fopen("C:\\Users\\PC\\Documents\\Inteiros.txt", "r");
if(f==NULL)
{
printf("Erro\n");
return 0;
}
int numbers[100], num, i=0;
while(fscanf(f, "%d", &num)>0)
{
numbers[i]=num;
i++;
}
fclose(f);
printf("%d numbers were read\n", i);
SelectionSort(numbers, 61);
for(int i=0;i<61;i++)
{
printf("%d --> %d\n", i, numbers[i]);
}
FILE *f2=fopen("C:\\Users\\PC\\Documents\\Inteiros2.txt", "w");
if(f==NULL)
{
printf("Erro\n");
return 0;
}
fwrite(numbers, sizeof(int), 61,f2);
fclose(f2);
}