Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks
- Note: Assuming that the records in file is in below format
- <PC1 name (string, containing spaces)>
- <PC1 clock rate (integer)>
- <PC1 memory (integer)>
- <PC2 name>
- ..
- ..
- ..
- //Code
- #include<stdio.h>
- #include<string.h>
- //structure representing a PC
- typedef struct PC{
- char name[20];
- int clock_rate;
- int memory;
- char *description;
- } PC;
- //method to read pc info from a file, fill the array, return the number of
- //records read.
- //assuming that the file is in below format
- //<PC name>
- //<clock speed (integer)>
- //<memory (integer, in TB)>
- //...
- int getpcs(FILE* file, PC array[50]){
- int count=0;
- char name[20];
- int clock;
- int memory;
- //looping until EOF is encountered, reading a line including spaces
- while(fscanf(file,"%[^\n]s\n",name)!=-1){
- //successfully read pc name, so there must be a clock rate and memory
- //reading that also
- fscanf(file,"%d\n",&clock);
- fscanf(file,"%d\n",&memory);
- //creating a PC object, filling the data
- PC pc;
- strcpy(pc.name,name);
- pc.clock_rate=clock;
- pc.memory=memory;
- pc.description=NULL;
- //adding to array, incrementing count
- array[count]=pc;
- count++;
- }
- //returning count
- return count;
- }
- int main(){
- //code to test the above method.
- //creating an array of PC objects
- PC array[20];
- //getting name of file to read
- printf("Enter filename: ");
- char filename[20];
- scanf("%s",filename);
- //opening file for reading
- FILE *fp=fopen(filename,"r");
- //checking if file opened correctly
- if(fp==NULL){
- //error
- printf("file not found\n");
- return 0;
- }
- //reading data from file
- int count=getpcs(fp,array);
- printf("Read values:\n");
- //displaying all values in the array
- for(int i=0;i<count;i++){
- printf("PC: %d\n",i);
- printf("Name: %s\n",array[i].name);
- printf("Clock rate: %d GHz\n",array[i].clock_rate);
- printf("Memory: %d TB\n",array[i].memory);
- printf("Description: %s\n\n",array[i].description);
- }
- return 0;
- }
- /*OUTPUT*/
- Enter filename: pc.txt
- Read values:
- PC: 0
- Name: Intel core i7
- Clock rate: 20 GHz
- Memory: 1 TB
- Description: (null)
- PC: 1
- Name: Intel core i5
- Clock rate: 3 GHz
- Memory: 1 TB
- Description: (null)
- PC: 2
- Name: Intel core i7 gen 7
- Clock rate: 7 GHz
- Memory: 2 TB
- Description: (null)
- PC: 3
- Name: Intel core i3
- Clock rate: 2 GHz
- Memory: 1 TB
- Description: (null)
- /*pc.txt file used*/
- Intel core i7
- 20
- 1
- Intel core i5
- 3
- 1
- Intel core i7 gen 7
- 7
- 2
- Intel core i3
- 2
- 1
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement