'create a binary file after sorting a numbers with names

I'm trying to wirte a C Program, which sorting list of numbers with names from txt file and write it in a bin file but the problem is that i can't write the bin file

the txt file :

45 Sam 788 Maria 421 Adam 96 Ziad

#include<stdio.h>
#include<stdlib.h>
struct student
{
    char name[20];
    int id;
} st[200];
void main()
{
    int cnt;
    struct student IN;
    FILE *fp;
    int i=0,size,j;
    char ch;

    fp=fopen("file.txt","r");
    if(fp==NULL)
    {
        printf("\n Error \n");
        exit(0);
    }
    while(ch!=EOF)
    {
        fscanf(fp,"%d%s",&st[i].id,st[i].name);
        ch=fgetc(fp);
        i++;
    }

    printf(" %d objects were read.", i);
    size=i-1;
    for(i=1; i<size; ++i)
        for(j=0; j<size-i; j++)
            if(st[j+1].id<st[j].id)
            {
                IN=st[j];
                st[j]=st[j+1];
                st[j+1]=IN;
            }
    fp=fopen("file_1.bin","wb");
    fp=fopen("file_1.bin","rb");
    for(i=0; i<size; i++)
        fprintf(fp,"%d %s \n",st[i].id,st[i].name);
    printf("\n the file has already been created. \n \n");

}


Solution 1:[1]

I tested your code a bit. Indeed it doesn't print anything in the file for a very simple reason: when you open the file it's not to write but to read.

Let's go back to the end of your code.

fp=fopen("file_1.bin", "wb");
fp=fopen("file_1.bin", "rb");
for(i=0; i<size; i++)
    fprintf(fp,"%d %s \n",st[i].id,st[i].name);
printf("the file has already been created.");

You open your file the first time with the mode "wb". This means that you are asking to write to the file. The fopen function returns a pointer to a FILE element that you store as the variable fp. But then you open the file a second time, but in "rb" mode. This mode is dedicated to reading only. Again you store the return in the variable fp. Doing this overwrites the old value and replaces it with the new one. The problem is this line. From the moment you store in fp a pointer to a FILE that has a read-only mode you can't write. You just have to delete this line and the file will be written.

Purely as an indication, you should pay attention to the return of your functions. Also any open file must be closed (here using the fclose function).

Here is the manual to familiarize yourself with fopen: https://man7.org/linux/man-pages/man3/fopen.3.html

PS: there is something to be revised in your algorithm ?

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Pierre