Thread: File I/O - problem reading in

  1. #1
    Registered User
    Join Date
    Sep 2009
    Posts
    16

    File I/O - problem reading in

    Hey there,

    I'm writing my final lab project for my programming class and I'm running into a problem.
    I need to read in employee information line by line from an existing file. The file opens and reads info in, but the distribution of the info on the line is staggered through the fields, and random numbers and letters show up on some lines while others are left blank. I'm getting desperate because my teacher even give us a hint, and our textbook doesn't explain how you are supposed to read in line by line from a file.
    Any help would be really appreciated.

    Thanks!
    Emily

    Code:
    #include <stdio.h>
    #include <string.h>
    #define MAX 7
    
    typedef struct
    {
    	char name [30];
    	char title [30];
    	double salary;
    	int years;
    }EMPLOYEE;
    
    
    void print_back(EMPLOYEE values[], int number_employees);
    void calculate_salary(EMPLOYEE values[], int number_employees);
    void get_retirees(EMPLOYEE values[], int number_employees);
    
    int main()
    {
    	int option, foo;
    	char filename [15];
    	
    	printf("\nPlease select an option from the menu below.");
    	printf("\n********************************************");
    	printf("\n1. Read employee information from an existing file");
    	printf("\n2. Write employee information to a new or existing file");
    	printf("\n\nPlease enter your selection: ");
    	scanf("%d", &option);
    	
    	if (option == 1) /*read*/
    	{
    		printf("\nPlease enter the name of the file (format: myfile.txt): ");
    			foo = scanf("%s", filename);
    			if (foo != 0)
    			{
    				FILE *input_file;
    				int i;
    				
    				input_file = fopen(filename,"r"); /*open*/
    				
    				if (input_file != NULL)
    				{
    					int i=0, count;
    					EMPLOYEE employees [MAX];
    					int number_employees=0;	
    								
    					while (fgets(employees[i].name, 30, input_file) != NULL)
    					{
    						i++;
    						fgets(employees[i].title, 30, input_file);
    						fscanf(input_file, "%lf", &employees[i].salary);
    						fscanf(input_file, "%d", &employees[i].years); /*buffer thing*/
    						number_employees++;			
    					}
    				
    					print_back(employees, number_employees);
    					calculate_salary(employees,number_employees);
    					get_retirees(employees, number_employees);
    				}
    				else
    				{
    					printf("\nFile failed to open, quitting!");
    				}
    				
    				
    			}
    	}
    	else if (option == 2) /*write*/
    	{
    		FILE *output_file;
    		int number_employees, i;
    		char lastname [15];
    	
    		printf("\nThank you.");
    		printf("\nPlease enter the name of the file to write to (format myfile.txt): ");
    		scanf("%s", filename); /*information entered stored in str "filename"*/
    		printf("\nHow many employees will you be entering: ");
    		scanf("%d", &number_employees);
    		
    		EMPLOYEE employees [number_employees];
    		
    		output_file = fopen(filename, "a"); /*open file*/
    		
    		
    		printf("\nFile successfully opened.");
    		printf("\nPlease enter employee information.");
    		
    		for(i=0; i < number_employees; i++) /*get info from user to print to "filename"*/
    		{
    		printf("\nEmployee Name: ");
    		scanf("%s%s", employees[i].name, lastname);
    		strcat(employees[i].name, " ");
    		strcat(employees[i].name, lastname);
    		fprintf(output_file, "%s\n", employees[i].name);
    		printf("\nEmployee Title: "); /*possibility of multiple word titles, later...*/
    		scanf("%s", employees[i].title);
    		fprintf(output_file, "%s\n", employees[i].title);
    		printf("\nSalary: ");
    		scanf("%lf", &employees[i].salary);
    		fprintf(output_file, "%0.2f\n", employees[i].salary);
    		printf("\nYears Employed: ");
    		scanf("%d", &employees[i].years);
    		fprintf(output_file, "%d\n", employees[i].years);
    		}
    		
    		fclose(output_file); /*close file*/
    	
    		printf("\nFile successfully written.  Retrieve entered data from file %s.", filename);
    	}
    	else
    	{
    		printf("\nInvalid selection, quitting!\n");
    	}
    	
    	printf("\nThank you for employee-fying.  Have a nice day.\n");
    	
    	return(0);
    }
    /*print back employee information*/
    void print_back(EMPLOYEE values[], int number_employees)
    {
            int i;
    
            printf("\nEmployee Information");
            printf("\n********************\n");
            printf("\nEmployees entered: %d\n", number_employees);
    
            for (i=0; i < number_employees; i++)
            {
                    printf("\nName: %s", values[i].name);
                    printf("\nTitle: %s", values[i].title);
                    printf("\nSalary: $%0.2lf", values[i].salary);
                    printf("\nYears Employed: %d\n", values[i].years);
            }
    }
    /*this function performs all salary information*/
    void calculate_salary(EMPLOYEE values[], int number_employees)\
    {
            int i;
            double total=0, average=0;
    
            for (i=0; i < number_employees; i++)
            {
                    total += values[i].salary;
            }
    
            average = total / number_employees;
    
            printf("\nYearly salary expense: $%0.2f", total);
            printf("\nAverage of employee salaries: $%0.2f", average);
    }
    void get_retirees(EMPLOYEE values[], int number_employees)
    {
            int i, retirees=0;
    
            printf("\n\nEmployees near retirement:");
    
            for (i=0; i < number_employees; i++)
            {
                    if (values[i].years >= 15)
                    {
                            printf("\n%s", values[i].name);
    			retirees++;
                    }
            }
    
    	printf("\nNumber of employees near retirement: %d", retirees);
    }

  2. #2
    Jack of many languages Dino's Avatar
    Join Date
    Nov 2007
    Location
    Chappell Hill, Texas
    Posts
    2,332
    Code:
                               while (fgets(employees[i].name, 30, input_file) != NULL)
    					{
    						i++;
    						fgets(employees[i].title, 30, input_file);
    						fscanf(input_file, "%lf", &employees[i].salary);
    						fscanf(input_file, "%d", &employees[i].years); /*buffer thing*/
    						number_employees++;			
    					}
    fgets() will read a whole line. So, don't read the whole line into title, but into a temporary char array that is long enough to hold the whole line. Then, you can parse the temp char array and break it into the specific fields you need.

    edit: rereading, I think you said there is one field per line, but the data on the lines is not predictable. It would help if you posted the input file.
    Last edited by Dino; 12-08-2009 at 03:19 PM.
    Mainframe assembler programmer by trade. C coder when I can.

  3. #3
    Registered User
    Join Date
    Sep 2009
    Posts
    16
    hey,
    i'm not quite sure what you mean, only because i am as they say a newbie. i don't know how to do what you suggested.
    emily

  4. #4
    Jack of many languages Dino's Avatar
    Join Date
    Nov 2007
    Location
    Chappell Hill, Texas
    Posts
    2,332
    Can you post the input file?
    Mainframe assembler programmer by trade. C coder when I can.

  5. #5
    Registered User
    Join Date
    Sep 2009
    Posts
    16
    sure, thanks for looking
    Code:
    emily leblanc
    student
    20000.00
    2
    mo moussa
    illustrator
    40000.00
    10

  6. #6
    Jack of many languages Dino's Avatar
    Join Date
    Nov 2007
    Location
    Chappell Hill, Texas
    Posts
    2,332
    but the distribution of the info on the line is staggered through the fields, and random numbers and letters show up on some lines while others are left blank.
    I don't see this in the input file.
    Mainframe assembler programmer by trade. C coder when I can.

  7. #7
    Registered User
    Join Date
    Sep 2009
    Posts
    16
    sorry, i probably didn't word it correctly, i'm in the middle of studying for calc final and bio on top of this so i'm alittle frazzled. this is what comes up when i read it in:

    Code:
    Please select an option from the menu below.
    ********************************************
    1. Read employee information from an existing file
    2. Write employee information to a new or existing file
    
    Please enter your selection: 1
    
    Please enter the name of the file (format: myfile.txt): dookie.txt
    
    Employee Information
    ********************
    
    Employees entered: 3
    
    Name: emily leblanc
    
    Title:
    Salary: $0.00
    Years Employed: 9094572
    
    Name:
    
    Title: student
    
    Salary: $20000.00
    Years Employed: 2
    
    Name: lustrator
    
    Title: mo moussa
    
    Salary: $0.00
    Years Employed: 9093056
    
    Yearly salary expense: $20000.00
    Average of employee salaries: $6666.67
    
    Employees near retirement:
    emily leblanc
    
    lustrator
    
    Number of employees near retirement: 2
    Thank you for employee-fying.  Have a nice day.

  8. #8
    Registered User
    Join Date
    Sep 2009
    Posts
    16
    i know the spacing is off, i'm going to fix that just before i submit it.

  9. #9
    Registered User
    Join Date
    Sep 2009
    Posts
    16
    again thank you so much for helping me, i really appreciate it.

  10. #10
    Registered User
    Join Date
    Oct 2008
    Location
    TX
    Posts
    2,059
    There are two things in your code that jump out - one is the newline leftover on the input stream after the last fscanf() causing the next call to fgets() to read a blank line. The other is that employee index i is being incremented before reading all the data for an employee. The fix is to put a newline at the end of the fscanf() format specifier and move the employee index i all the way to the bottom.
    Code:
    fscanf(input_file, "%d\n", &employees[i].years); /*buffer thing*/
    i++;

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Subtle(?) File I/O Problem
    By cecomp64 in forum C Programming
    Replies: 9
    Last Post: 07-16-2008, 11:39 AM
  2. Post...
    By maxorator in forum C++ Programming
    Replies: 12
    Last Post: 10-11-2005, 08:39 AM
  3. problem in reading alphabets from file
    By gemini_shooter in forum C Programming
    Replies: 6
    Last Post: 03-09-2005, 01:49 PM
  4. Replies: 3
    Last Post: 03-04-2005, 02:46 PM
  5. Problem reading file.
    By Hulag in forum C Programming
    Replies: 11
    Last Post: 10-24-2004, 09:39 AM