- 2070 Chaitra · 4 marks
Display records sorted by name from file
Short answer
Read name and roll from records.txt using fscanf into a struct array. Sort ascending by name with bubble sort using strcmp (swap whole struct when out of order). Print the sorted list.
Write the program to display the records in sorted order, sorting is performed in ascending order with respect to name using data files concept.
Logic. The records (name and roll) are stored in a text file records.txt, one record per line. The program reads them into an array of structures with fscanf(), sorts the array in ascending order of name with strcmp() (bubble sort, swapping whole structures) and displays them.
#include <stdio.h>
#include <string.h>
#define MAX 100
struct rec {
char name[30];
int roll;
};
int main(void)
{
struct rec r[MAX], t;
int n = 0;
FILE *fp = fopen("records.txt", "r");
if (fp == NULL) {
printf("Cannot open records.txt\n");
return 1;
}
while (n < MAX && fscanf(fp, "%29s %d", r[n].name, &r[n].roll) == 2)
n++;
fclose(fp);
for (int i = 0; i < n - 1; i++)
for (int j = 0; j < n - 1 - i; j++)
if (strcmp(r[j].name, r[j + 1].name) > 0) {
t = r[j]; r[j] = r[j + 1]; r[j + 1] = t;
}
printf("%-10s %s\n", "Name", "Roll");
for (int i = 0; i < n; i++)
printf("%-10s %d\n", r[i].name, r[i].roll);
return 0;
}
Output (records.txt had the lines: Ram 1, Sita 2, Bibek 3, Hari 4, Anil 5)
Name Roll
Anil 5
Bibek 3
Hari 4
Ram 1
Sita 2
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Sort array ascending in FORTRAN · Computer Programming, chapter 11 · asked 2×
- Employee text file; sort into binary file · Computer Programming, chapter 10
- I/O functions used with data files · Computer Programming, chapter 10 · asked 2×
- College records with nested date structure · Computer Programming, chapter 8
- Read records until end; show nth record · Computer Programming, chapter 10 · asked 2×
- Student records with two functions · Computer Programming, chapter 8
- Student records file with CRN search · Object Oriented Programming, chapter 8
- File stream; student binary file program · Object Oriented Programming, chapter 8
- Write and display 10 employees using file · Object Oriented Programming, chapter 8
- Student file displayed in descending marks order · Object Oriented Programming, chapter 8