I have to create a program in C and not C++, that allows the user to create a file that stores names and numbers, displays them and sorts the dates by names or numbers using Bubble sorting. I know how to create a program that sorts names and numbers that are entered from a keyboard, but don't know how to do it whit a file. If anyone knows please at least show me an example. Thanks.

This is the program i written so far.

#define _CRT_SECURE_NO_WARNINGS
#include<stdlib.h>
#include<stdio.h>
#include<conio.h>

FILE *f;
struct dates{
	char name;
	int num;
    }list;
    int s,i;
int create(){
   
   

  printf("Enter total numbers of elements: ");
  scanf("%d",&s);

  f=fopen("Bubble.txt", "w");

  printf("Enter %d elements:\n ",s);
  for(i=0;i<s;i++){
	  printf("Name:\n");
          scanf("%s",&list.name);
	  fflush(stdin);

	  printf("Number:\n");
	  scanf("%d",&list.num);
	  fwrite(&list,sizeof(list),1,f);
  }
	  fclose(f);
	  return 0;
}
	  
  
int display()
 {      
  f=fopen("Bubble.txt", "r");
  
  printf("---Names and numbers:--\n ");
  printf("| Nr.| Nume   | Numar |\n");
  i=1;
  fread(&list,sizeof(list),1,f);
  while (!feof(f))
  {
  
  printf(" | %d  | %6s | %5d |\n", 
   i++,
   list.name,
   list.num);
  fread(&list,sizeof(list),1,f);
  
  }
  printf("\n");
  fclose(f);
  return 0;
}
  

int bubble()
{   

    //Bubble 	sorting function
    
    return 0;
}	 

  int main(void)
	  {
	int option;
	while (1)

	{
	printf("           ------- M E N I U ------\n");
	printf("         ----- Choose an option ----\n");
        printf("\n");
	printf("              1 - Create the file\n");
	printf("              2 - Display the file\n");
	printf("              3 - Bubble sorting\n");
	printf("              4 - Exist the program\n");
	scanf("%d",&option); fflush(stdin);
	switch (option)
	{
	case 1: create(); break;
	case 2: display(); break;
        case 3: bubble(); break;
	case 4: exit(1);

	default: printf("Alegeti optia corect\n"); break;
	} }
	   _getch();
	}

Dani AI

Generated

Short answer: read the whole file into memory, sort the in-memory array, then write it back. pointed you in the right direction; the bugs in 's code are typical and easy to fix: wrong scanf usage for arrays, undefined use of fflush(stdin), opening binary data with text-mode flags, using feof() to control reads, fixed small buffers, and an inner bubble loop that allows the code to compare arr[k+1] when k is the last index (out-of-bounds).

Common, concrete fixes and checks:

  • Open binary records with "rb"/"wb" when using fread/fwrite (or use text I/O with fprintf/fscanf consistently).
  • Compute record count with fseek/ftell or read into a dynamically resized array with realloc; do not assume a fixed small size.
  • Drive reads by the return value of fread/fscanf (not feof()) and check fopen/fread/fwrite return values.
  • Use scanf("%63s", rec.name) (no ampersand for an array) or fgets() to allow spaces and avoid buffer overflow.
  • Correct bubble bounds: for i in [0..n-2], inner for j in [0..n-2-i] so j+1 is always valid.
  • Prefer qsort() for production code (faster, less error-prone).

A minimal, safe pattern (reads all records, bubbles by name or number, writes back):

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct { char name[64]; int value; } Record;

size_t read_records(const char *fn, Record **out) {
    FILE *f = fopen(fn, "rb"); if (!f) return 0;
    if (fseek(f, 0, SEEK_END)!=0) { fclose(f); return 0; }
    long bytes = ftell(f); if (bytes<=0) { fclose(f); return 0; }
    size_t n = bytes / sizeof(Record);
    *out = malloc(n * sizeof(Record)); if (!*out) { fclose(f); return 0; }
    rewind(f); size_t r = fread(*out, sizeof(Record), n, f); fclose(f);
    if (r!=n) { free(*out); *out = NULL; return 0; } return n;
}

void write_records(const char *fn, Record *a, size_t n) {
    FILE *f = fopen(fn, "wb"); if (!f) return;
    fwrite(a, sizeof(Record), n, f); fclose(f);
}

void bubble_sort(Record *a, size_t n, int by_name) {
    for (size_t i=0;i+1<n;i++) for (size_t j=0;j+1<n-i;j++) {
        int cmp = by_name ? strcmp(a[j].name,a[j+1].name) : (a[j].value - a[j+1].value);
        if (cmp>0) { Record t=a[j]; a[j]=a[j+1]; a[j+1]=t; }
    }
}

If you want, post your file format (binary vs text) and I can show the matching read/write and a simple menu integration.

Recommended Answers

All 2 Replies

I know how to create a program that sorts names and numbers that are entered from a keyboard, but don't know how to do it whit a file.

Read the file into memory, then sort it as you normally would. While it's possible to sort the file without loading it into memory completely (Google "external sorting"), such methods are quite a bit more complex than in-memory sorting. I also don't believe that your requirements are asking for an external sort.

This is an updated version of the program with a bubble sorting function in it, but it doesn't sort the way it should. If someone knows what I did wrong, please tell me.

#define _CRT_SECURE_NO_WARNINGS
#include<stdlib.h>
#include<stdio.h>
#include<conio.h>

FILE *f;
struct dates{
	char name[10];
	int num;
    }list, list2;
    int s,i;
int create(){
   
   

  printf("Enter total numbers of elements: ");
  scanf("%d",&s);

  f=fopen("Bubble.txt", "w");

  printf("Enter %d elements:\n ",s);
  for(i=0;i<s;i++){
	  printf("Name:\n");
          scanf("%s",&list.name);
	  fflush(stdin);
	  printf("Number:\n");
	  scanf("%d",&list.num);
	  fwrite(&list,sizeof(list),1,f);
  }
	  fclose(f);
	  return 0;
}
	  
  
int display()
 {      
  f=fopen("Bubble.txt", "r");
  
  printf("---Names and numbers:--\n ");
  printf("| Nr.| Nume   | Numar |\n");
  i=1;
  fread(&list2,sizeof(list2),1,f);
  while (!feof(f))
  {
  
  printf(" | %d  | %6s | %5d |\n", 
   i++,
   list2.name,
   list2.num);
  fread(&list2,sizeof(list2),1,f);
  
  }
  printf("\n");
  fclose(f);
  return 0;
}
  

int bubble()
{   

    //Bubble 	sorting function
	      f=fopen("Bubble.txt", "r");
              struct dates arr[5];
              fread(&list2,sizeof(list2),1,f);
              int i=0;

           
           while (!feof(f))
           {
              arr[i]=list2;
              i++;
             fread(&list2,sizeof(list2),1,f);
           }

int j,k;

for(j=0; j<i; j++)
  {
     for(k=0; k<i; k++)
       {
          if(arr[k].num>arr[k+1].num)
          {
               struct dates temp=arr[k]; 
               arr[k]=arr[k+1];
               arr[k+1]=temp;
          }
      }
   }


  fclose(f);
  f=fopen("Bubble.txt", "w");
  

    for(j=0; j<i; j++)
     {
          struct dates temp=arr[j];
          fwrite(&temp,sizeof(temp),1,f);
      }

   fclose(f);
   return 0;
}	 

  int main()
	  {
			int option;
	while (1)

	{
	printf("         ------- M E N I U --------\n");
	printf("         ----- Choose an option ----\n");
        printf("\n");
	printf("           1 - Create the file\n");
	printf("           2 - Display the file\n");
	printf("           3 - Bubble sorting\n");
	printf("           4 - Exist the program\n");
	scanf("%d",&option); fflush(stdin);
	switch (option)
	{
	case 1: create(); break;
	case 2: display(); break;
        case 3: bubble(); break;
  	case 4: exit(1);

	default: printf("Choose the correct option\n"); break;
	} }
	   return 0;
	}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.