Trouble Reading Data from Files

This is a discussion on Trouble Reading Data from Files within the C Programming forums, part of the General Programming Boards category; I have a file with numbers that I need for calculations and want to open the file, read the data ...

  1. #1
    Registered User
    Join Date
    Apr 2006
    Posts
    9

    Trouble Reading Data from Files

    I have a file with numbers that I need for calculations and want to open the file, read the data and put the data in specific variables. The file has non-zero values, but my program just outputs zeros . . . please help!

    The text file will look like this:
    Params
    1
    2
    3
    4
    5
    6,7
    Data
    1,1
    2,2
    3,2
    4,4
    5,6

    Code:
    //Lunar Lander Phase 2
    
    #include <stdio.h>
    
    int main()
    
    {
    //	Declare variables
    
    float G, vi, v, B, tstep, duration[100000], burnrate[100000], m, temp1, temp2, j;
    int mi, ve, D, S, i = 0;
    
    
    FILE *inFile;
    
    inFile = fopen("LAND2.txt", "r");	
    if (inFile == NULL)
    {
    printf("\nFailed to open the file.\n");			
    exit (1);
    }
    
    else
    {
    printf("\nThe file LAND2.txt was opened successfully.\n");
    fscanf (inFile, "Params \n");				
    fscanf (inFile, "%f", &G); 				
    fscanf (inFile, "%f\n", &vi);			
    fscanf (inFile, "%f\n", &B);			
    fscanf (inFile, "%f\n", &tstep);			
    fscanf (inFile, "%d\n", &mi);				
    fscanf (inFile, "%d\n", &ve);			
    fscanf (inFile, "%d,", &D);			
    fscanf (inFile, "%d", &S);			
    fscanf (inFile, "Data \n");  
    
    for ( i =0; i <= D; i++)
    {
    fscanf(inFile, "%d,%d\n", &temp1, &temp2);						
    duration[i]=temp1;
    printf("%d\n", duration[i]);
    		
    burnrate[i]=temp2;
    printf("%d\n", burnrate[i]);
    }
    fclose (inFile);				
    }
    
    return 0;
    }

  2. #2
    cwr
    cwr is offline
    Registered Luser cwr's Avatar
    Join Date
    Jul 2005
    Location
    Sydney, Australia
    Posts
    869
    I'd suggest using fgets() to read each line into a buffer and then read on that buffer, you can then use sscanf and check the return code to verify each line was well formed and read in successfully. sscanf returns the number of items successfully read in.

  3. #3
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,006
    I'd do something more like this in the else clause.
    Code:
          if ( fscanf (inFile, "Params %f %f %f %f %d %d,%d Data", 
                       &G, &vi, &B, &tstep, &mi, &ve, &D, &S) == 7 )
          {
             for ( i = 0; i < D; ++i )
             {
                if ( fscanf(inFile, "%f,%f\n", &duration[i], &burnrate[i]) == 2 )
                {
                   printf("%g %g\n", duration[i], burnrate[i]);
                }
             }
          }
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  4. #4
    Registered User
    Join Date
    Jan 2006
    Location
    Berkeley, Ca
    Posts
    195
    This might be a little ghetto, but it could work

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    #define MAXLINE 10
    
    int main(void)
    
    {
    
        char buff[MAXLINE];
    
        char temp1[] = "Params\n";
        char temp2[] = "Data\n";
    
        FILE *inFile;
    
        inFile = fopen("LAND2.txt", "r");       
        if (inFile != NULL)
        {
            while (fgets(buff, sizeof(buff), inFile) != NULL)
    	    if(strncmp(buff,temp1,sizeof(buff)) == 0)
    		/*store data */
    
    	rewind(inFile);
    
    	while (fgets(buff, sizeof(buff), inFile) != NULL)
                if(strncmp(buff,temp2,sizeof(buff)) == 0)
    		/*store data */
    
    
        }
    
    /*probably should check for more errors*/   
    
    	fclose (inFile);                                
        
    
        return 0;
    }

  5. #5
    Registered User
    Join Date
    Jan 2006
    Location
    Berkeley, Ca
    Posts
    195
    Quote Originally Posted by cwr
    I'd suggest using fgets() to read each line into a buffer and then read on that buffer, you can then use sscanf and check the return code to verify each line was well formed and read in successfully. sscanf returns the number of items successfully read in.
    Or I could wait for Dave to beat me to the punch.

  6. #6
    Registered User
    Join Date
    Apr 2006
    Posts
    9
    Hey, I tried this and it didn't was successful . .. but didn't give me the array, and said that the if(fscanf) bit had "too many arguments for format"

    Any suggestions?


    Quote Originally Posted by Dave_Sinkula
    I'd do something more like this in the else clause.
    Code:
          if ( fscanf (inFile, "Params %f %f %f %f %d %d,%d Data", 
                       &G, &vi, &B, &tstep, &mi, &ve, &D, &S) == 7 )
          {
             for ( i = 0; i < D; ++i )
             {
                if ( fscanf(inFile, "%f,%f\n", &duration[i], &burnrate[i]) == 2 )
                {
                   printf("%g %g\n", duration[i], burnrate[i]);
                }
             }
          }

  7. #7
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,006
    Quote Originally Posted by CConfusion
    Hey, I tried this and it didn't was successful . .. but didn't give me the array, and said that the if(fscanf) bit had "too many arguments for format"

    Any suggestions?
    Yeah, get rid of the 8th S parameter. (I thought about editing that the other day, but tried to let it slip. Perhaps it is me that is slipping.)
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  8. #8
    Registered User
    Join Date
    Apr 2006
    Posts
    9
    Okay, I made the data read it in and I get the parameters for the first bit, but with the loop for the duration[i] and burnrate[i] arrays my program doesn't output the right stuff .. . this is what i've got currently.

    And thanks for the help!

    Code:
    int main()
    
    {
    	//	Declare variables
    
    		float G, vi, v, B, tstep, duration[100000], burnrate[100000], m, temp1, temp2, h = 500, total = 0, a, j;
    		int mi, ve, D, S, i;
    
    
    		FILE *inFile;
    		FILE *outFile;															//Declare a file outFile
    
    		inFile = fopen("LAND2.txt", "r");								//	Open file LAND2.txt to read
    
    		if (inFile == NULL)
    		{
    			printf("\nFailed to open the file.\n");					//	If the file doesn't exist print out can't open file and exit.
    			exit (1);
    		}
    
    //	Read in values for Params and Data
    
    		else
    		{
    				printf("\nThe file LAND2.txt was opened successfully.\n\n");
    
       			fscanf (inFile, "Params\n");								// Read the Params line (on the first line)
    
    				fscanf (inFile, "%f\n", &G); 								//	Read the first parameter, gravitational acceleration (on the next line)
    				fscanf (inFile, "%f\n", &vi);								// Read the second parameter,initial downward velocity (on the next line)
    				fscanf (inFile, "%f\n", &B);								// Read the third parameter, initial burn rate (on the next line)
    				fscanf (inFile, "%f\n", &tstep);							// Read the fourth parameter, time step (on the next line)
    				fscanf (inFile, "%d\n", &mi);								// Read the fifth parameter, initial fuel mass (on the next line)
    				fscanf (inFile, "%d\n", &ve);								// Read the sixth parameter, fuel exhaust speed (on the next line)
    				fscanf (inFile, "%d,%d\n", &D,&S);							// Read the Data and Solutions values
    				
    				printf ("%f\n%f\n%f\n%f\n%d\n%d\n%d,%d\n", G, vi, B, tstep, mi, ve, D, S);
    				
    				fscanf (inFile, "Data\n");   							// Read the Data line
    
    		for ( i = 0; i < D; i++ )
             {
    				fscanf(inFile, "%f,%f\n", &temp1, &temp2);				//	Read in burnrate andduration til EOF
    				
    				temp1=duration[i];
    				printf("%f\n", duration[i]);
    				
    				temp2=burnrate[i];
    				printf("%f\n", burnrate[i]);		
    			}
    
    			fclose (inFile);														//	Close the file
    		}

  9. #9
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,006
    This is what I was messing with.
    Code:
    //Lunar Lander Phase 2
    #include <stdio.h>
    
    float duration[100000], burnrate[100000];
    
    int main()
    {
       static const char filename[] = "LAND2.txt";
       FILE *file = fopen(filename, "r");   
       if ( file != NULL )
       {
          float G, vi, B, tstep;
          int mi, ve, D, i;
    
          printf("The file %s was opened successfully.\n", filename);
          if ( fscanf(file, "Params %f %f %f %f %d %d,%d Data", 
                      &G, &vi, &B, &tstep, &mi, &ve, &D) == 7 )
          {
             for ( i = 0; i < D; ++i )
             {
                if ( fscanf(file, "%f,%f\n", &duration[i], &burnrate[i]) == 2 )
                {
                   printf("%g %g\n", duration[i], burnrate[i]);
                }
             }
          }
          fclose(file);           
       }
       else
       {
          perror(filename);
       }
       return 0;
    }
    
    /* my output
    The file LAND2.txt was opened successfully.
    1 1
    2 2
    3 2
    4 4
    5 6
    */
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  10. #10
    Registered User
    Join Date
    Apr 2006
    Posts
    9
    Okay, I think my problem is that the file I'm reading will not always have 1,1 as it's starting values .. . so when you use fscanf ( .. . ....) ==2, it wont work for mine . . . (if I'm understanding what that line means correctly)

  11. #11
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,006
    LAND2.txt
    Code:
    Params
    10
    20
    30
    40
    50
    60,5
    Data
    10,10
    20,20
    30,20
    40,40
    50,60
    My output
    Code:
    The file LAND2.txt was opened successfully.
    10 10
    20 20
    30 20
    40 40
    50 60
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  12. #12
    Registered User
    Join Date
    Apr 2006
    Posts
    9
    Okay, I got it thanks. My next (and hopefully last) problem is my file doesn't give me actual numbers when I run the last bit. This is what I have: (the problem is somewhere after the "outFile" bit.

    Code:
    //Lunar Lander Phase 2
    
    #include <stdio.h>
    
    //Declare function prototypes
    float masschange(float duration, float burnrate, float total);
    
    int main()
    
    {
    	//	Declare variables
    
    		float G, vi, B, tstep, duration[100000], burnrate[100000], h = 500, total = 0, a, j;
    		int mi, ve, D, S, i;
    
    
    		FILE *inFile;															//Declare a file outFile
    		FILE *outFile;
    
    		inFile = fopen("LAND2.txt", "r");								//	Open file LAND2.txt to read
    
    		if (inFile == NULL)
    		{
    			printf("\nFailed to open the file.\n");					//	If the file doesn't exist print out can't open file and exit.
    			exit (1);
    		}
    
    //	Read in values for Params and Data
    
    		else
    		{
    			if ( fscanf (inFile, "Params\n %f\n %f\n %f\n %f\n %d\n %d\n %d,%d\n Data\n", &G, &vi, &B, &tstep, &mi, &ve, &D, &S) == 8)
          	{
             	for ( i = 0; i < D; ++i )
    	         {
       	         if ( fscanf(inFile, "%f,%f\n", &duration[i], &burnrate[i]) == 2 )
          	      {
             	      printf("%2g %2g\n", duration[i], burnrate[i]);				//Check the arrays to make sure the data was read correctly
                	}
             	}
          	}
    			
    			fclose(inFile);
    		}
    
    
    	outFile = fopen("LAND2Soln.txt", "w");								//Make a file named LAND2Soln.txt to write to
    
    	for (i = 0; i <= D; ++i)												//Counting up by one for duration/burnrate values
    	{
    		float m, v;																//	Find t for h = 0.0, set as td
    		m = masschange(duration[i], burnrate[i], total);
    	
    		if (outFile == NULL)
    		{
    			printf("Unable to open file.\n");								//If the file doesn't exist end.
    			return 1;
    		}
    		
    		else													//As long as the file exists, write the calculated velocity to it.
    		{
    			for (j = 0; j <= duration[i]; j = j + tstep)				//j keeps track of the amount of time each duration has run for
    			{
          		a = (((m*G) - (burnrate[i]*ve))/m);
    				v = v + (a*j);
          		      		
          		printf("%f\n", v);
    				fprintf(outFile, "%f\n", v);											//calculates the nth velocity
    
    				h = h - (v*j);
    
    				if (h <= 0) 													//Stops when h = 0.
    				{
    					return 1;
    				}
       		}
    		}
    
    	}
    
    	fclose(outFile);
    
    	return 0;
    }
    
    //	Define Custum Functions:
    
    
    float masschange(float duration, float burnrate, float total)
    {
    	float mass = burnrate*duration;			//	From Data array (needs a loop that goes through duration, and jumps burnrate after duration is up . . .
    	total = total + mass;
    	return total;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 7
    Last Post: 02-02-2009, 07:27 AM
  2. Replies: 48
    Last Post: 09-26-2008, 04:45 AM
  3. Reading data from a text file
    By Dark_Phoenix in forum C++ Programming
    Replies: 8
    Last Post: 06-30-2008, 03:30 PM
  4. added start menu crashes game
    By avgprogamerjoe in forum Game Programming
    Replies: 6
    Last Post: 08-29-2007, 02:30 PM
  5. having trouble reading data from a file
    By Unregistered in forum C++ Programming
    Replies: 5
    Last Post: 11-08-2001, 11:15 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21