luc092.c (1337B)
1 /* 2 * Author : Amit Dutta <amitdutta4255@gmail.com> 3 * Date : 08 Feb 2026 4 * Repo : https://github.com/notamitgamer/bsc 5 * License : MIT License (See the LICENSE file for details) 6 */ 7 8 /* Write a program to store names in a file. Display the n-th name in the list, where n is read from the keyboard. 9 */ 10 /* Let Us C, Chap- 19 (File Input/Output), Qn No.: B(h) */ 11 12 /* This file is auto-generated by a bot. */ 13 /* This code is not compiled; it is for reference only. */ 14 15 16 #include <stdio.h> 17 #include <stdlib.h> 18 #include <string.h> 19 #include <ctype.h> 20 21 void create_name_file(); 22 23 int main() 24 { 25 FILE *fp; 26 char name[50]; 27 int n, current = 0, found = 0; 28 29 create_name_file(); 30 31 printf("Enter value of n to find n-th name: "); 32 scanf("%d", &n); 33 34 fp = fopen("names.txt", "r"); 35 if (!fp) exit(1); 36 37 // Assuming one name per line 38 while (fgets(name, sizeof(name), fp) != NULL) 39 { 40 current++; 41 if (current == n) 42 { 43 printf("The %d-th name is: %s", n, name); 44 found = 1; 45 break; 46 } 47 } 48 49 if (!found) 50 printf("Record not found (Only %d names exist).\n", current); 51 52 fclose(fp); 53 return 0; 54 } 55 56 void create_name_file() 57 { 58 FILE *f = fopen("names.txt", "w"); 59 fprintf(f, "Alice\nBob\nCharlie\nDavid\nEve\nFrank\n"); 60 fclose(f); 61 }