Write a Modular C Programming code for Storing Data into the File overwrite
A file will be created in the name computer.txt in the same location
Question) Vishal owns a cyber café, where he has ‘N’ number of computers stored in a file. Since Vishal is lazy to write the details of ‘N’ computers on paper, he stores the
details of computers in a file. Please help Vishal to store the details of the computers
and perform the below operations.
*Display the details of all computers.
Refer To Notes: Notes: File Handling in C programming | Operations in Files
CODE:
#include<stdio.h> #include<stdlib.h> void write_to_file(FILE *p); void read_from_file(FILE *p); void computers_details(FILE *p); int main() { FILE *p; write_to_file(p); read_from_file(p); return 0; } void write_to_file(FILE *p) { char computer_name[20]; int ram,windows,i,n; p=fopen("computer.txt","w"); printf("Enter the number of computers: "); scanf("%d",&n); for(i=1;i<=n;i++) { printf("\n+++++++++++++++++++++++++++++++++++++++++++++++++\n"); printf("\nEnter the Details of computer %d: \n",i); printf("ENTER COMPUTER NAME: "); scanf("%s",computer_name); printf("ENTER THE RAM OF THE COMPUTER: "); scanf("%d",&ram); printf("ENTER THE WINDOWS VERSION: "); scanf("%d",&windows); printf("+++++++++++++++++++++++++++++++++++++++++++++++++\n"); fprintf(p,"\n%s\t%d\t%d\n",computer_name,ram,windows); } fclose(p); } void read_from_file(FILE *p) { char computer_name[20]; int ram,windows; p=fopen("computer.txt","r"); printf("computer name\RAM\tWindows\n"); while(!feof(p)) { fscanf(p,"%s %d %d\n",computer_name,&ram,&windows); printf("%s\t%d\t%d\n",computer_name,ram,windows); } fclose(p); }
OUTPUT
Enter the number of computers: 3 +++++++++++++++++++++++++++++++++++++++++++++++++ Enter the Details of computer 1: ENTER COMPUTER NAME: virus ENTER THE RAM OF THE COMPUTER: 8 ENTER THE WINDOWS VERSION: 8 +++++++++++++++++++++++++++++++++++++++++++++++++ +++++++++++++++++++++++++++++++++++++++++++++++++ Enter the Details of computer 2: ENTER COMPUTER NAME: kali ENTER THE RAM OF THE COMPUTER: 16 ENTER THE WINDOWS VERSION: 3 +++++++++++++++++++++++++++++++++++++++++++++++++ +++++++++++++++++++++++++++++++++++++++++++++++++ Enter the Details of computer 3: ENTER COMPUTER NAME: parrot ENTER THE RAM OF THE COMPUTER: 32 ENTER THE WINDOWS VERSION: 6 +++++++++++++++++++++++++++++++++++++++++++++++++ computer nameRAM Windows virus 8 8 kali 16 3 parrot 32 6 Process returned 0 (0x0) execution time : 35.651 s Press any key to continue.
Refer : C Programming HackerRank all solutions for Loops | Arrays | strings
Please find some more codes of Loops, Condition Statements, 1D Arrays, 2D Arrays, Strings, Pointers, Data Structures, Files, Linked lists, MISC, Solved model question papers & Hacker Rank all solutions on the below page:
Top 100+ C Programming codes – KLE Technological University