102k views
4 votes
In this lab, you open a file and read input from that file in a prewritten C program. The program should read and print the names of flowers and whether they are grown in shade or sun. The data is stored in the input file named flowers.dat. Instructions Ensure the source code file named Flowers.cpp is open in the code editor. Declare the variables you will need. Write the C statements that will open the input file flowers.dat for reading. Write a while loop to read the input until EOF is reached. In the body of the loop, print the name of each flower and where it can be grown (sun or shade). Execute the program by clicking the Run button at the bottom of the screen.

User Ben Roux
by
3.5k points

1 Answer

1 vote

Answer:

#include <stdio.h>

#include <string.h>

void main( )

{

array flowerProp[2];

FILE *fp; // file pointer

char flower[255]; // creating a char array to store data

fp = fopen("flowers.dat","r");

if (fp == NULL){

printf("File flower.dat does not exist");

return;

}

// assuming the growing condition is next line to the flower name.

while(fscanf(fp, "%s", flower)!=EOF){

flowerProp.push(flower);

if (flowerProp.length == 2){

printf("%s: %s\\ ", flowerProp[0], flowerProp[1]);

memset(flowerProp, 0,0);

}

}

fclose (fp );

}

Step-by-step explanation:

The algorithm creates a pointer to the memory location to the file starting position, the character size is used to get a string from the file line by line. Then it opens and checks if the file exists.

If the file exists, the while gets the name and growth condition of the flower, saves it to an array, prints the name and condition, and clears the array for the next flower type in the loop.

User Egor Egorov
by
3.4k points