Thread: Need help - copying data from file.

  1. #1
    Registered User
    Join Date
    Apr 2007
    Posts
    8

    Need help - copying data from file.

    Hey guys,
    just doing a coursework assignment and need some help.

    My code so far:
    Code:
    #include "stdio.h"
    
    int main(void)
    {
    	FILE *fptr;
    
    	if((fptr = fopen("table.txt", "r")) == NULL) //Open file.
    	{
    	    printf("\n\nCould not open the table file.\n\n"); //error message.
    	}
    
    	char str1[20], k=0;
    
    	while(k != '\n')//Skips the first line (column headers)
    	{
    		if(fscanf(fptr, "%c", &k) == EOF) //Or breaks anyway if end of file is reached.
    		{
    			printf("\n END OF FILE REACHED\n\n");
    			break;
    		}
    	}
    
    	float c02[100], total=0.0;
    	int END = 0;
            int j;
    	int i;
    	for(j=0; END == 0; j++) //breaks if end of file is reached
    	{
    		for(i=0; i<26; i++)
    		{
    			if(fscanf(fptr, "%c", &k) == EOF)
    				END = 1;
    		}
    		fscanf(fptr, "%f", &c02[j]);
    		if(END == 0)
    			total = total + c02[j];
    	}
    
    	printf("\nTotal C02: %f kg\n", total);
    	printf("\nCO2 Rations: %f", total / 2500);
    
    
    	getchar(); //PAUSE
    
    	return 0;
    }
    Basically, this looks at a file - 'table.txt' which has amounts of CO2 at 26 spaces from the left. This code calculates the total amount of CO2 (i.e. add up numbers in all lines - 26 spaces from the left). And calculates CO2 rations (1 ration = 2500 kg/n co2).

    But i also need to basically copy all information in the file.

    This is the file:
    Code:
    Fuel/Activity  Unit       kg CO2 / unit
    Petrol         1 litre    2.3
    Oil            1 litre    2.7
    Coal           1 kg       2.4
    Wood           1 kg       0.0
    Electricity    1 kWhr     0.4
    Natural Gas    1 kWhr     0.2
    Air travel     1 mile     0.3
    I need the program to copy the left column and the right column (fuel/activity, and kg CO2/unit).

    Can anyone help?

    Thanks.
    Noori.
    Last edited by Dave_Sinkula; 05-27-2007 at 05:19 PM. Reason: Changed [quote][/quote] tags to [code][/code] tags to preserve whitespace.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    Use fgets() and sscanf to deal with a whole line.
    Code:
    while ( fgets( buff, sizeof buff, fptr ) != NULL ) {
        if ( sscanf( &buff[26], "&#37;f", &co2 ) == 1 ) {
            total += co2;
        }
    }
    Skip the first line with another fgets() call.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    Some things to note about your code:
    • Standard header files, such as stdio.h, are usually included with angle brackets.
      Code:
      #include <stdio.h>
      Double quotes, as you have it, are typically reserved for user-created header files.
    • Declaring variables in the middle of blocks is C99. This means that if you want compatibility with C89, an older version of C, you should declare all of your variables at the beginning of a block. (A block is delimited by { and }.)
    • Code:
      	if((fptr = fopen("table.txt", "r")) == NULL) //Open file.
      	{
      	    printf("\n\nCould not open the table file.\n\n"); //error message.
      	}
      What happens if the file could not be opened? You print an error message, sure, but then the program just keeps on executing. You'd likely get a segmentation fault when you try to read from the file. You should probably exit the program if the file could not be opened.

      Also, most error messages are usually printed to stderr. You could use fprintf(stderr, ...) or perror(...) to do this.
    • Code:
      	while(k != '\n')//Skips the first line (column headers)
      	{
      		if(fscanf(fptr, "&#37;c", &k) == EOF) //Or breaks anyway if end of file is reached.
      		{
      			printf("\n END OF FILE REACHED\n\n");
      			break;
      		}
      	}
      Asuming you want to use that loop instead of fgets(), you could use something like
      Code:
      while(fscanf(fptr, "%c", &k) == 1 && k != '\n');
      or
      Code:
      while((k = fgetc(fptr)) != '\n' && k != EOF);
      (Note that k would then have to be an int in the last case.)

      Just a suggestion.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. xor linked list
    By adramalech in forum C Programming
    Replies: 23
    Last Post: 10-14-2008, 10:13 AM
  2. Replies: 48
    Last Post: 09-26-2008, 03:45 AM
  3. Inventory records
    By jsbeckton in forum C Programming
    Replies: 23
    Last Post: 06-28-2007, 04:14 AM
  4. gcc problem
    By bjdea1 in forum Linux Programming
    Replies: 13
    Last Post: 04-29-2002, 06:51 PM
  5. what does this mean to you?
    By pkananen in forum C++ Programming
    Replies: 8
    Last Post: 02-04-2002, 03:58 PM