Loading a File in C++: Tips & Techniques

  • C/C++
  • Thread starter Spectre32
  • Start date
  • Tags
    C++ File
In summary, the program is designed to open a file for reading using the fReadOpen function, which prompts the user to enter a valid file name and checks for its existence. If the file is not found, the program displays an error message and prompts the user to enter a valid file name again. Once a valid file name is entered, the program uses the get_data function to read the values from the file and store them in an array. The program then uses various functions to sort the data, calculate the average, median, variance, and standard deviation, and finally displays the results to the user.
  • #1
Spectre32
136
0
Loading a File in C

Ok here is my code:

Code:
FILE  *fReadOpen( void )
/*
    purpose: open file for reading
    goal state: fReadOpen returns pointer to file
*/
{ /* begin fReadOp */
  /* data object declarations */
    char  FileName[80];  /* input file name */
    FILE  *pInFile;  /* file pointer */
    int  NoSuchFile;  /* logical check for FileName existence */

  /* algorithm */
	 printf( "\nPlease enter the file name to open for reading.\n ==> " );
	 do
		{ /* get FileName */
			 fflush( stdin );
			 scanf( "%[^\n]", FileName );
			 fflush( stdin );
		  /* check for existence */
			 NoSuchFile = ( (pInFile = fopen( FileName, "r" ) ) == NULL );
		  /* print message if file not found */
			 if  ( NoSuchFile )
				{ /* begin if NoSuchFile */
					 printf( "\n%s not found."
								"\nPlease input valid file name.\n ==> ", FileName );
				} /* end if NoSuchFile */
		}
	 while  ( NoSuchFile );
		
	 return( pInFile );

} /* end fReadOpen */

//********************************************************************
void get_data( double input_val[], int *parray_int)
/*
    purpose: continue on with file opening process
    goal state: return an array with via the point array_int
*/
{    // begin get_data
	// variable dictionary
	double acquire;       // being read by fscanf
	double value = 0;     // "value" for the fscanf statement
	FILE   *pInfile;       //  file from above function
	
	// algorithm 
		// open file for reading
			pInfile = fReadOpen();

		// loop for reading values 
			
			*parray_int = 0;
			do
			{ 
				acquire = fscanf(pInfile,"%f", &value);
				if (acquire == 1)
				{
					input_val[*parray_int] = value;
					*parray_int = *parray_int + 1;
				}
			} while (acquire == 1);

			// close file
			fclose( pInfile );

}   // end get_data


Yeah I know its on the large size but I'm kinda confused. My professor gave us that whole File loading thing,a nd i created a data file from notepad. When i run to the program It just sits there and does nothing. So i started to debug and added printf's in those lines. the last line that the printf worked on was the one prior to the return statement, now perhpas my data format is incorrect, but I'm pretty sure I'm straight with that. Does anyone have any Ideas?
 
Last edited:
Technology news on Phys.org
  • #2
Where's main()?
 
  • #3
it's up a little bit.. i only posted those two functions... here is the rest: to that point

Code:
main()
{ // begin main
  // variable declarations
	 double input_val[N];       // input values
	 int array_int;            // number of input values
	 int ave;				  // average
	 int median;			 // median
	 int variance;			// Valance
	 int std_dev;		   // Standard Deviation

  // algorithm
		displayheader();
		get_data( input_val, &array_int);
		sort_data(input_val, array_int );
		calculations( input_val, array_int, &ave , &median, &variance, &std_dev);
		display(input_val, array_int, ave , median, variance, std_dev);
  // display end of program message
	printf("\n\n***** End of program\n***** ");

	return (0);

} // end main

//********************************************************************
void  displayheader( void )

I edited out my header file for securit reasons... o:)
 
  • #4
Right now your doing file i/o the C way. If your looking to do it the C++ way you'll want to something like this:

Code:
#include <iostream>
#include <fstream>

using namespace std ;

int main( int argc , char **argv) {

int field1, field2, field3 ;

ifstream infile("file.in") ;

while( !infile.eof() ) {
   infile >> field1 >> field2 >> field3 ;
   cout << field1 << field2 << field3 << endl ;
}

return 0;

}
 
  • #5
Well it needs to be C then, sorry for the miss leading title. This is what my professor wants us to use.
 
  • #6
Did you enter a proper filename for the input file which should be in the current directory of the executable file?
 
  • #7
Something like this should work:

Code:
#include <stdio.h>
#include <stdlib.h>

int main( int argc , char **argv ) {

FILE *infile ;

infile = fopen( "testin" , "r" ) ;

int field1, field2, field3 ;

if( infile == NULL ) {
        printf("Error Reading File\n") ;
        exit(0) ;
}

while( fscanf( infile , "%i %i %i\n" , &field1, &field2, &field3 ) != EOF ) {
        printf( "Field1: %i\nField2: %i\nField3: %i\n\n" , field1, field2, field3) ;
}

fclose( infile ) ;

return 0 ;

}
 
Last edited:
  • #8
Yeha I'm pretty sure cause i typed in differt ones and it was very quick to find out it was not there. When i type din the proper extentions it just sat there and didn't do anything. Also I just took your code and compiled it( with a few minor changes), and it worked well, but it going to be hard to interigrate it into my current code. Also liek everyone else got it to work and I'm pretyt sure there are not this many problems.

I'm just kinda fustrated, i can't use this code.
 
Last edited:
  • #9
The thing that is bugging me is the acquire variable. Your setting its value through fscanf, but you never check for EOF. Put some printf statements inside of the do while loop and see what happens.
 
  • #10
I did... and they all displayed. I did that before I posted. Even As i said the only one that didn't display was the one after the Return xxxxx...
 
  • #11
What do you mean by "the one after the Return xxxxx..."?
 
  • #12
Code:
  /* algorithm */
	 printf( "\nPlease enter the file name to open for reading.\n ==> " );
	 do
		{ /* get FileName */
			 fflush( stdin );
			 scanf( "%[^\n]", FileName );
			 printf( "crap2");
			 fflush( stdin );
		  /* check for existence */
			 NoSuchFile = ( (pInFile = fopen( FileName, "r" ) ) == NULL );
			 printf( "crap3");
		  /* print message if file not found */
			 if  ( NoSuchFile )
				{ /* begin if NoSuchFile */
					 printf( "\n%s not found.");
				    printf( "crap4");
					printf( "\nPlease input valid file name.\n ==> ", FileName );
				} /* end if NoSuchFile */
		}
	 while  ( NoSuchFile );
	 printf( "crap5");
		
	 return( pInFile );

} /* end fReadOpen */

And this is what it displayed:

Please enter int he file for reading
===> data.txt
crap2crap3crap5


Sooo... i guess ... well I don't know what this means. Out side of crap4 is nothign majro cause the file was indeed valid... Sooo again I'm back to square one.
 
Last edited:
  • #13
after the return ( pInFile) i had a printf("whatever"); and it didn't get displayed.
 
  • #14
After you return a value the function exits.

Is the pointer being returned correctly?
 
  • #15
Well i assume not, because I had a print statement after the return and nothing happend. the pointer is used in the next function that I had posted up top. I'm pretty sure it's pasted correctly.
 
Last edited:
  • #16
Hmmmm I just put a prinf statement in the next function below the whole "file getting one" and when i ran it it displayed the print F on the same line as the printf for the entering in the file. Now I'm slightly confused.

EDIT It just started working soo i got to debug some more, thanks for the help :)
 
Last edited:

1. How do I open and read a file in C++?

To open a file in C++, you can use the ifstream class from the <fstream> header. First, declare an ifstream object and pass in the name of the file you want to open as a parameter. Then, use the open() method to open the file. To read from the file, you can use the getline() function or the ifstream object's extraction operator (>>). Don't forget to close the file when you're done using it!

2. How do I check if a file has been successfully opened?

To check if a file has been successfully opened, you can use the is_open() method of the ifstream object. This method will return a bool value indicating whether the file was opened successfully or not. You can also use the fail() method to check for any errors that may have occurred during opening.

3. How can I handle errors while loading a file?

There are a few ways to handle errors while loading a file in C++. One way is to use the fail() method to check for any errors during opening or reading the file. You can also use the exceptions() method to enable exceptions for file errors, so that you can catch and handle them in your code. Another option is to use the errno global variable, which stores error codes for file operations.

4. How do I write to a file in C++?

To write to a file in C++, you can use the ofstream class from the <fstream> header. First, declare an ofstream object and pass in the name of the file you want to write to as a parameter. Then, use the open() method to open the file. To write to the file, you can use the ofstream object's insertion operator (<<). Don't forget to close the file when you're done writing!

5. How can I efficiently load a large file in C++?

One way to efficiently load a large file in C++ is to use the seekg() method of the ifstream object. This method allows you to move the file pointer to a specific position in the file, so you can read from a specific location instead of reading the entire file. You can also use the read() method to read a specific number of bytes from the file. Another option is to use memory mapping, which allows you to access the file's contents as if it were in memory. This can be more efficient for large files, but it is more advanced and may require more code.

Similar threads

  • Programming and Computer Science
Replies
4
Views
740
  • Programming and Computer Science
3
Replies
75
Views
4K
  • Programming and Computer Science
Replies
10
Views
5K
  • Programming and Computer Science
Replies
2
Views
2K
  • Programming and Computer Science
Replies
4
Views
8K
  • Programming and Computer Science
Replies
4
Views
1K
  • Programming and Computer Science
Replies
13
Views
2K
  • Programming and Computer Science
Replies
4
Views
2K
  • Programming and Computer Science
Replies
4
Views
2K
  • Programming and Computer Science
Replies
2
Views
1K
Back
Top