File I/O Help

Discussion in 'C' started by BNoble, May 11, 2011.

  1. BNoble

    BNoble New Member

    Joined:
    May 11, 2011
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    I am working on a lab for one of my classes. I cant quite figure out how to use File I/O correctly. I know how to open the file but not store the information in an array of structures. I understand you use the fscanf function but im not sure how to use it. I think after I figure out the File I/O situation I can finish the rest on my own. Here is what I have so far.

    Code:
    include<stdio.h>
    #include<stdlib.h>
    #include<string.h>
    
    /*	
    Lab 22 - Structures
    Name: Brandon Noble
    */ 
    
    struct _City{
    	char name[32];
    	char state[32];
    	int temp;
    };
    
    
    void main() {
    
    	
    
    	FILE *fp;
    	fp = fopen("cities.txt", "r");
    
    	if(fp==NULL){
    		printf("Failed to open file");
    	}
    	else {
    		struct _City arr[100];
    		while(!feof(fp)){
    			result = fscanf(fp, "%s", 
    		
    	}
    
    
    
    }
    
    here is my file

    Code:
    Detroit Michigan 76
    Miami Florida 89
    Boston Massachusetts 54
    Houston Texas 78
    Borwnwood Texas 75
    Akron Ohio 56
    Langsing Michigan 56
    Tampa Florida 88
    Orlando Florida 76
    Chlemsford Massachusetts 57
    Cleveland Ohio 56
    Barrow Alaska -12
    Stephenville Texas 75
    Fairbanks Alaska 23
    Jacksonville Florida 100
    
    and here is my instructions

    This lab will read in data from a file and store it in an array of structures. There is a file called cities.dat on the web site that contains a list of cities. This includes its name, temperature, and state. The information for each is stored on one line similar to the following:
    Detroit Michigan 76
    Read in this data and stored the information in an array of structures. The structure will hold the information for a single city.
    Create a function called displayCity that is passed a single structure and displays that city using the following format. Notice the use of the comma between the city and the state. Use this function to display the cities.
    Detroit, Michigan has a temperature of 76
    In the main function, call the display function in a loop to display all of the cities. Precede the list with a title of your choosing.

    thanks for all your help.
     
  2. eriyer

    eriyer New Member

    Joined:
    Jan 22, 2011
    Messages:
    32
    Likes Received:
    0
    Trophy Points:
    0
    I have posted a program to a similar query using fwrite() / fread() - Please refer Advance C - File Handling posted by harim.

    eriyer
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice