NEWS: Total Picture Views: 147068 | Total Article Views: 155683 | Top 5 Most Popular Article: 1. Am I Stuck Algorithm with Becker Robot | 2. How to read a JSON and work with it | 3. PickUpThings with Becker Robot | 4. Encrypted Data GUI (Download .Zip) | 5. Create Wall and Things with Becker

Structure Part 3 C

Description:

In this example I will be showing and to read a file and print it in the console while using structure.

Cust.txt:
Lisa 519898989 400
jhon 905787878 200

Code:

// include
#include <stdio.h>
#include <string.h>

// add the prototype of gets to avoid the warning extern function
char *gets(char *dst); 

// define the user data type (Customer)
typedef struct{
 // define the members 
	char name[30]; 
	char phone[10]; 
	int age; 

} Customer; 

// define a function

void printCustomer(Customer c){
	printf("Name: %s\n Phone: %s\n age: %d\n",c.name, c.phone,c.age ); 
}


// a function to load data from a text file so that
// each record uses a line and the space is the delimiter ( separates the fields)
void load( char filename[10], Customer customers[]){
	// creating a temporary variable for holding a record 
	char tmpName[30];
	char tmpPhone[10];
	int tmpAge;
	int counter;

	// declare a file pointer
	FILE *input= fopen(filename, "r+");

	//check if the file opened succesfully
    if (input==NULL)
		perror ("Error opening file");
    else{
		counter=0; 
		// continue in reading the file til the EOF
		while(!feof(input)){
			strcpy(tmpName," ");
			fscanf(input, "%s %s %d", tmpName,tmpPhone,&tmpAge);
			if(strcmp(tmpName," ")!=0){
				strcpy(customers[counter].name,tmpName);
				strcpy(customers[counter].phone,tmpPhone);
				customers[counter].age=tmpAge;
				counter++;
				}
		}
    fclose(input);
    }
}
int main(int argc, char *argv[]){
	// defined an array for holding data of two customers
	Customer myCustomers[2];
	
	//intialize the age of all customers to -1. 
	// this intialization enables us to determine if data
	// are loaded or not
    for(int i=0; i<2; i++)myCustomers[i].age=-1;
  
	// get the input from the file cust.txt
	char myFileName[10]="cust.txt"; 
	load(myFileName, myCustomers);

	

	//prints the data loaded 
	
	for(int i=0; i<2;i++){
		if(myCustomers[i].age!=-1)
			printCustomer(myCustomers[i]);

	}

}
Attachments: None

Tags: Reading File Structure

Total Views: 852

My name is Jean-Mathieu

I created this website so other people could enjoy finding useful stuff easier. If you have any question do not hesitate to contact me.

jean8mathieuCreated on 01/28/15


affiliate_link

Disclosure: We are a website that needs compensation to operate like any other website on the internet.
We may receive consideration for our reviews but we are totally unbiased and do not accept paid reviews or fake reviews claiming to be something they are not.