Вы находитесь на странице: 1из 21

Scope of Variables

We define a "block" as that part of your code enclosed by braces { }. Each block is considered to be its own little stand-alone program; its own entity. Any variable defined within a set of braces is said to be local to that block (it is also called automatic ) and its value is recognized only within that block. The part of a program in which the value of a variable is recognized is called its "scope." #include <stdio.h> int main ( ) { //entering main's block int x; x=5; { //the beginning of a new "block" int x; //this is NOT the same "x" as the one defined outside the block x=20; //Assign the value 20 to this "new" x printf("\nThe value of x in this block is %d",x); //the value 20 would be printed //when this block is exited this x will "die" } //exiting the inner block printf("\nThe value of x after exiting the block is %d",x); return 0; } //the value 5 will be printed

In the above example, if the two statements just inside the "main" block were omitted, the program would not even compile. Consider the following example when those 2 statements are omitted. #include <stdio.h> int main ( ) { //note the 2 statements int x; and x=5; are missing; { //the beginning of a new "block" int x; //this is NOT the same "x" as the one defined outside the block x=20; //Assign the value 20 to this "new" x printf("\nThe value of x in this block is %d",x); //the value 20 would be printed //when this block is exited this x will "die" } // the statement below would cause a compile error because you are referencing x and

there is // NO x in this block printf("\nThe value of x after exiting the block is %d", x ); return 0; } Using variables that are NOT defined within a block Any time that you reference a variable in a block the compiler will use the "closest" declaration of that variable. This means that if the variable is defined within that very block it will use that blocks definition of that variable. If it cannot find a declaration within that block, then it will look for it in the next closest enclosing block, etc. until it finds it. If it cannot find it within the function at all (and, remember, that main( ) is also a function), then it looks to see if it is a global variable (defined a little later). If it cannot find it as a global variable, then you get a "serious" error and the program will not compile. That is what happened in the second example above; the variable x was referenced in main's block and the compiler could find no declaration for the variable x anywhere. Consider the following example: #include <stdio.h> int main ( ) { int x; x=5; { //Note that the variable x below is NOT declared within this block. //So the compiler would look for the "first" x it can find in the next enclosing // block and use its storage location. Thus the value 20 below would be written // over top of the value 5 x=20; //Assign the value 20 to this "new" x - replaces the value 5 printf("\nThe value of x in this block is %d",x); //the value 20 would be printed //when this block is exited this x does NOT "die" because it was //declared outside this block } //Note, now that when the block was exited, the storage location x whose value WAS 5 before it //entered the block above has had its value changed to 20. So when the statement below is //executed, the value 20 would print.

printf("\nThe value of x after exiting the block is %d",x); return 0; } Consider the example below. #include <stdio.h> int main ( ) { int x, y; y=-7; x=5; { enclosing

//the value 20 will be printed

//Note that the variable x below is NOT declared within this block. //So the compiler would look for the "first" x it can find in the next // block and use its storage location. Thus the value 20 below would be

written // over top of the value 5 //However, the variable y IS declared within this block, so a new storage location //is created for it. The variable y declared here is NOT the same y that was used //in main. It is a totally new location that "dies" when the block is exited. int y; this x=20; y = 32; //block //Assign the value 20 to this "new" x - replaces the value 5 //The "new" y gets the value 32, the "old" y is NOT touched. //a "new" y is declared (the "old" y is still there, just NOT used in

printf("\nThe value of x in this block is %d", x); //the value 20 would be printed //when this block is exited this x does NOT "die" because it was //declared outside this block printf("\nThe value of y in this block is %d", y); } //Note, now that when the block was exited, the storage location x whose value WAS 5 before it //entered the block above has had its value changed to 20. So when the statement below is //the value 32 would be printed

//executed, the value 20 would print. printf("\nThe value of x after exiting the block is %d", x); printed //the value 20 will be

//However, the variable y defined within the inner block "died" when the block was exited. //So the printf statement below would reference the "old" y and use its corresponding value. printf("\nThe value of y after exiting the block is %d", y); return 0; } In the example below, there are three nested blocks and three references to the variable x. #include <stdio.h> int main ( ) { //block 1 the main block int x; x=5; { int x; exited x=30; { //give this new x the value 30 //block 3, nested inside block 2 //Note that the variable x below is NOT declared within this block. //So the compiler would look for the "first" x it can find in the next enclosing // block (in this case it is block 2) and use its storage location. Thus the // value 20 below would be written over top of the value 30 x=20; //Assign the value 20 to this "new" x - replaces the value 30 printf("\nThe value of x in this block is %d",x); //the value 20 would be printed //when this block is exited this x does NOT "die" because it was //declared outside this block } //exit block 3 //block 2, "nested" inside block 1 //this is a new x, so the old x is "forgotten" until this block is //the value -7 will be printed

//Note, now that when the block was exited, the storage location x whose value WAS 30 before it //entered the block above has had its value changed to 20. So when the statement below is //executed, the value 20 would print. printf("\nThe value of x after exiting block 3 is %d",x); printed } //exit block 2 (the x defined in block 2 "dies" ) printf("\nThe value of x after exiting block 2 is %d",x); return 0; } Note: Any time a variable is declared within a block, the compiler "forgets" any other variable with the same name that is declared outside that block. Any reference made to this variable will always use the storage location that has been declared inside this block. However, when the block is exited, any variable that had been declared within that block "dies". Global Variables These are variables that are declared outside and above a function. Once these variables have been declared, they are recognized by every function that follows the declaration. However, the above rule in the note still applies; that is, if the same variable name appears again inside a block, it is the new declaration that is recognized inside the block. If the name of a global variable appears as a parameter in a function declaration, a local variable is created and the global variable is not recognized or used in any way. Consider the following example where the integer x has been declared above main( ) #include <stdio.h> void PrintsIt( void ); //prototype for function PrintsIt( ) void CalcG( int); //prototype for function CalcG( ); int x; //declaring this "above and outside" of main makes it global to every // function that follows int main ( ) { x=5; //sets the "global" value of x to 5 //the value 5 will be printed //the value 20 will be

//the beginning of a new "block"

int x; //this is NOT the same "x" as the global x x=20; //Assign the value 20 to this "new" x printf("\nThe value of x in this block is %d",x); //the value 20 would be printed //when this block is exited this x will "die" } printf("\nThe value of x after exiting the block is %d",x); //the value 5 will be printed PrintsIt( ); //call the PrintsIt function, but do not give it any information CalcG( 34); return 0; } //call the CalcG function and pass it a copy of the value 34

void PrintsIt( void ) //no input paramters { //enter a "new block" int y ; //this variable y is local to this block y = x * 7; //no x is declared within this block so compiler would look for the // "closest" declaration that it could recognize. Because it will not recognize //any x declared INSIDE any other block, it looks to see if there is an x //declared ABOVE and OUTSIDE this block. It searches above and finds // there IS an x declared. So, it is THIS value of x that is used. //The global value of x is 5 printf("\nThe values of x and y are %d and %d", x, y ); //prints 5 and 35 return; } void CalcG( int x ) variable { printf("\The value of x in this function is %d", x ); // the value 34 will print return; } Note: Variables that declared OUTSIDE functions are recognized as being "global" to only those functions that follow (are BELOW) the declaration of the variables //note that there is a global variable of x, but redeclaring this //as x "overrides" the global x so that the function does NOT even //know that the global value of x exists.

Example: #include <stdio.h> void f( void ); void g( void ); int x; //x is global to everything that follows

int main( ) { . . . }//end of main int y; // y is global to everything that follows but NOT to main ( ) void f( void ) {. . . . } int z; //z is global only to what is below and is not global to either main( ) or to f( ) void g( ) { . . } static Variables Variables that are declared upon entry to a block, "die" when the block is exited. That is, the storage that was allocated to these local variables is released when the block is exited. Global variables, of course, do not die until the program is terminated. There is a special kind of variable, however, that has its storage allocated the very first time that its containing function is called and does not die until the program ends. This variable also retains its value when the function is exited.

Example In the function below, the variable x is a static variable. Void fn( ) { int y = 17; and will always

// y is a local variable. It is "born" each time the function is called //have the starting value of 17 each time it is called. // It "dies" each time the function exits.

static int t = 5; once. At the time of the variable does

// t is a local, static variable. This means that it is "born" only //its "birth" it is given the value 5. When this function is exited, //not die it will keep whatever value it had when it exited. The

next time the //function is called, the variable will still have the value it had, when the // function exited. y = y + 23; t = t + 30; result will be 35 be later when //the function is called, because the "initial " value of t is what it was when the //function was last called. printf("\The value of y is %d", y); printf("\nThe value of t is %d", t); value 35 prints return; } Suppose the following program made several calles to this function ( in the interest of saving space, I did not copy the function and put it below main ( ) , I just put the prototype in for the funciton). //the value of 40 will print EVERY time //The first time the function is called the //y had a starting value of 17, so it is now 40; //the first time this function is called, t will have a value of 5 so this //however, there is no way of knowing for sure what this value will

#include <stdio.h> void fn (void ); //the prototype for the above function int main ( ) { int x, y; int t = 20; //this t was placed here to show that the t in main is NOT the same // t that is found in the function. fn( ); //call the function fn ( ); //call it again fn( ); //call it a 3rd time fn( ); //call it a 4th time printf("\nThe value of t is %d", t ); //this will print the value of the t found in main( ) //the value 20 will print every time the program runs return 0; } // end of main When the preceding program is run, the following display is on the screen The value of y is 40 The value of x is 35 The value of y is 40 keeps The value of x is 65 The value of y is 40 The value of x is 95 2nd call The value of y is 40 The value of x is 125 these 2 lines are a result of the First call to fn this is the 2nd call to fn. Note that y gets reinitialized but x value it had when it exited fn the first time x had kept the value 65 when it exited the function after the x had kept its value after the 3rd call, so it got bumped to 125

It is possible for several functions to have static variables with the same name. The compiler will keep these variables straight so that there is no confusion about which variable the function should use. Consider the below example where the functions f( ) and g ( ) have the a static variable with the same name. void f (void ) { static int x = 5; // the first time f is called, its static variable x gets a value 5 x = x + 2; // add 2 to f 's static variable x printf("\nInside f and its variable x has a value %d ", x ); return; } void g (void ) { static int x =12; // the first time g is called, its static variable x gets a

value 12 x = x + 7; // add 7 to g's static variable x printf("\nInside g and its variable x has a value %d ", x ); return; } int main( ) { int x = 13; // this is main's x and has NOTHING to do with either f's or g's f ( ); g( )' f( ); g( ); f( ); g( ); printf("\nThe value of x in main is %d", x); //prints 13 all the time! return 0; } When the above program is executed, the following is displayed on the screen Inside f and its variable x has a value 7 Inside g and its variable x has a value 19 Inside f and its variable x has a value 9 Inside g and its variable x has a value 26 Inside f and its variable x has a value 11 Inside g and its variable x has a value 33 The value of x in main is 13

File Input/Output
Input and Output to disk files using simple character I/O You must use the structure type FILE and allocate storage for a pointer for every file that you want opened or closed. The below program can be used to display the contents of any text file on the screen. It should NOT be used to display the contents of .obj or .exe files but can be used to display any .c or .cpp files. //This program will open a file and print every character to the screen // #include <stdio.h> #include <stdlib.h> //want to use the exit() function int main( )

{ int ch; FILE *fp;

//used to hold the input characters //allocate storage for one file pointer

fp=fopen("a:data.fil","r"); //open the file "data.fil" on the a: // drive as a "read" file if ( fp = = NULL) // if for some reason the file could not be opened { printf("\nThe file could not be opened for some reason"); exit(0); //quit the program! } while ((ch=fgetc(fp)) != -1) // the value 1 indicates that the EndOfFile EOF has been reached printf("%c",ch); fclose(fp); //good programmers close their files return 0; }

Input and Output to disk files that is more complicated than just inputting/outputting characters There are essentially 5 or 6 basic functions for use in reading from/writing to a disk. fopen( ) fread( ) fwrite( ) fclose ( ) fscanf( ) fprintf( ) feof ( )

// works just like scanf // works just like printf //used for testing to see if the end of the file has been reached

You also need a new pointer variable for a "type" that we have not yet discussed. This type is called FILE (note all capital letters). You use this type just like you would use int or float. You must have a "file pointer" for every file that you are accessing (either to read or write). In order to use a disk file, we say that the file has to be "open". When you request that a file be opened, you must specify the name of the file and how you plan to access it; either to read it or to write it. There are actually other options, but we will not consider them in this course. The system will take care of opening the file and setting up an input/output buffer to be used. This is really all automatic and you don't have to worry about it. However, you must supply a file pointer in order for it to "tie" your program to the file. This is done in the following manner: 1) FILE *fpin1, *fpin2; //setting up 2 input file pointers. Could be named

anything 2) fpin1=fopen("a:filename.ext","r"); //open the diskfile filename.ext

Statement 1) above sets up the storage space for 2 file pointers. Their names could have been anything, but I used fpin1 and fpin2 to indicate that I am going to use two input files. But, you could use names like: FILE *fpayroll, *fouput, *fstudents; //etc/ Statement 2) says to open (get ready to use) the file by the given name on the disk drive. Suppose that you had a file names payroll.dat that was on the a: drive and that you wanted to input from it. The open statement would look like the following: fpin1 = fopen("a:payroll.dat", "r"); //open the payroll file to read it If you wanted to create a disk file (write to it) you would write something like the following: fpout= fopen("a:lab5.dat","w"); //open the file lab5.dat on the a: drive If for some reason the files cannot be opened (e.g. is NOT on the disk in the drive, there is no room on the disk to write to, the disk is damaged, can't be read or written to, etc), then the system will return a value of 0 for the file pointer, that is, it returns a value of NULL. In order for you to keep your program from "crashing" if the program can't locate the disk file, then you would do something like the following: // make sure that the file called "payroll.dat" is on the disk in the a: drive when // you try to open it for reading. If the file can't be opened, print an error message and cancel // the program, that is, end it. fpin1=fopen("a:payroll.dat", "r"); //open the payroll file if ( fpin1 = = NULL) { printf("\nThe payroll.dat file could not be opened for some reason"); exit( 0 ); // quit the program!! Terminate!! Get out!! }

Some of the simplest functions to use are fprintf and fscanf. They are very similar to printf and scanf. Essentially the only difference is that there is an additional parameter that goes right before the format string; you must put the file pointer of the file you want to use right before the string.

Consider the following: Suppose that you wanted to input 3 exam grades for students and write them out to a (text) disk file. The following program code would accomplish just that: // store1.cpp // Input 3 exam scores for students and write them out to a disk file // Separate each grade in the file to make it easy to read them back in // Any time a negative test score is entered, there are no more grades to enter #include <stdio.h> int main() { int t1, t2, t3; //variables for the test scores FILE *fpout; // set up the file pointer to use for the output file fpout=fopen("a:grades.dat","w"); //open a file named grades.dat to write to on the floppy disk if(fpout = =NULL) // make sure that you can write to the disk, it may not be in the drive or // the disk might be full or damaged { printf("\nFor some reason the file grades.dat could not be opened on the A: drive"); exit(0); // and quit the program } // input the first set of grades. This is the "primer read" printf("\nEnter the 3 test scores separated by spaces. Enter 3 negative numbers if done "); scanf("%d %d %d" &t1,&t2, &t3); while( (t1>=0) && (t2>=0) && (t3>=0)) { fprintf(fpout, " %d %d %d ",t1, t2, t3); // note there are spaces before and after each number for later easier input printf("\nEnter the 3 test scores separated by spaces. Enter 3 negative numbers if done "); scanf("%d %d %d" &t1, &t2, &t3); // get 3 more test scores } fclose(fpout); return (0); } Once the file has been created you can access it. The test scores are stored in "text" format and are separated by spaces. This means that they can be input using the fscanf function.

The following program would read the above file and print the test scores on the screen. // input1.cpp // This program will read test scores from a disk file. It assumes that each student has 3 test scores // Each time the program tries to read 3 scores. If it is ever unsuccessful in doing that it will quit #include <stdio.h> int main() { int numread; //used to store the number of test scores read at a time int t1, t2, t3; //variables for the test scores FILE *fpin; // set up the file pointer to use for the output file fpin=fopen("a:grades.dat","r"); //open a file named grades.dat to input from on the floppy disk if(fpin = =NULL) // make sure that you can read the disk, it may not be in the drive or // the disk might be damaged, or the file may not be on the disk { printf("\nFor some reason the file grades.dat could not be opened on the A: drive"); exit(0); // and quit the program } numread=fscanf(fpin,"%d %d %d", &t1, &t2, &t3); // numread should be 3 because that is how many scores it is supposed to read at a time while(numread= = 3) //make sure that it was able to read 3 test scores { printf("\n t1= %d, t2= %d, t3= %d", t1, t2, t3); numread=fscanf(fpin,"%d %d %d", &t1, &t2, &t3); //note there is NO printf for a an input prompt because the user is NOT entering // the data. It is being read from a file } fclose(fpin); return (0); } Using fread( ) and fwrite() The use of structures makes it a lot easier to read and write from disk. The data is stored in what is called "binary" form and you have to remember to type the letter b after the r and w when you open to read or write the file. But, the primary convenience is that you don't have to list the individual structure elements. Let's look at the example above and construct an

example where the test scores are part of a structure. Then we will look at the code for writing to the disk if we did NOT treat the file as a binary file. The program will be VERY similar to the above. The parts that are different will be in bold. // store2.cpp // Input 3 exam scores for students and write them out to a disk file // The input fields will be part of a record structure. It is defined just above main // Separate each grade in the file to make it easy to read them back in // Any time a negative test score is entered, there are no more grades to enter #include <stdio.h> struct InRec { int t1, t2, t3; }; int main() { struct InRec grades; //set up a structure called grades to hold the 3 test scores FILE *fpout; // set up the file pointer to use for the output file fpout=fopen("a:grades.dat","w"); //open a file named grades.dat to write to on the floppy disk // NOTE: that it is opened as "w" and NOT "wb" which means you MUST list each field // individually when you write to the file if(fpout = =NULL) // make sure that you can write to the disk, it may not be in the drive or // the disk might be full or damaged { printf("\nFor some reason the file grades.dat could not be opened on the A: drive"); exit(0); // and quit the program } // input the first set of grades from the keyboard. This is the "primer read" printf("\nEnter the 3 test scores separated by spaces. Enter 3 negative numbers if done "); scanf("%d %d %d" &grades.t1,&grade.st2, &grades.t3); while( (grades.t1>=0) && (grades.t2>=0) && (grades.t3>=0)) { fprintf(fpout, " %d %d %d ",grades.t1, grades.t2, grades.t3); // note there are spaces before and after each number for later easier input // note that you HAD to list each field separately and identify the structure printf("\nEnter the 3 test scores separated by spaces. Enter 3 negative numbers if done "); scanf("%d %d %d" &grades.t1, &grades.t2, &grades.t3); // get 3 more test scores }

fclose(fpout); return (0); } To input information into a structure from a file that was created as a text file, you simply have to identify each field of the structure. The code for a program to read the above file would look like the following: // input2.cpp // This program will read test scores from a disk file. It assumes that each student has 3 test scores // Each time the program tries to read 3 scores. If it is ever unsuccessful in doing that it will quit // The data will be input from a standard text file into a data structure called grades #include <stdio.h> struct InRec { int t1, t2, t3; } int main() { struct InRec grades; //set up a structure called grades to hold the 3 test scores int numread; //used to store the number of test scores read at a time FILE *fpin; // set up the file pointer to use for the output file fpin=fopen("a:grades.dat","r"); //open a file named grades.dat to input from on the floppy disk if(fpin = =NULL) // make sure that you can read the disk, it may not be in the drive or // the disk might be damaged, or the file may not be on the disk { printf("\nFor some reason the file grades.dat could not be opened on the A: drive"); exit(0); // and quit the program } numread=fscanf(fpin,"%d %d %d", &grades.t1,&grades.t2,&grades.t3); // numread should be 3 because that is how many scores it is supposed to read at a time while(numread= = 3) { printf("\n t1= %d, t2= %d, t3= %d", grades.t1, grades.t2, grades.t3); numread=fscanf(fpin,"%d %d %d", &grades.t1, &grades.t2, &grades.t2) //note there is NO //printf for a prompt because the user is NOT entering // the data is being read from a file }

fclose(fpin); return (0); } The same work could be done using structures and writing to/reading from a binary file. This would allow you to use just the name of the structure instead of naming the individual fields. But, first, you will need to be introduced to the fwrite , fread, and feof functions. Their general format is as follows: fwrite(&nameOfStructure, sizeof (nameOfStructure),1, filepointer); fread(&nameOfStructure, sizeof (nameOfStructure),1, filepointer); feof( filepointer); With both the fwrite and fread functions you just have to give the address of the particular structure that you want the information stored into. Then, by giving the size of that structure, the computer will know how much information to either write or to read. The 1 is necessary to tell them to only read that many bytes 1 time. The filepointer tells it which file to write to or to read from. The feof function allows you to see if you reached the end of the file on your last read. To illustrate how these three functions are used, let's redo the output file example and input file example from before. It is important to understand, now, that these files MUST be opened as binary files. Therefore, you will HAVE to use "wb" and "rb" when you are writing to or reading from either of those files.

// store3.cpp // Input 3 exam scores for students and write them out to a disk file // The input fields will be part of a record structure. It is defined just above main // Separate each grade in the file to make it easy to read them back in // Any time a negative test score is entered, there are no more grades to enter #include <stdio.h> struct InRec { int t1, t2, t3; } int main() { struct InRec grades; //set up a structure called grades to hold the 3 test scores FILE *fpout; // set up the file pointer to use for the output file

fpout=fopen("a:grades.dat","wb"); //open a file named grades.dat as a binary file to write // to on the floppy disk // NOTE: that it is opened as "wb" which means you will be able to just use the // name of the structure when you write // individually when you write to the file if(fpout = =NULL) // make sure that you can write to the disk, it may not be in the drive or // the disk might be full or damaged { printf("\nFor some reason the file grades.dat could not be opened on the A: drive"); exit(0); // and quit the program } // input the first set of grades. This is the "primer read" printf("\nEnter the 3 test scores separated by spaces. Enter 3 negative numbers if done "); scanf("%d %d %d" &grades.t1,&grades.t2, &grades.t3); while( (grades.t1>=0) && (grades.t2>=0) && (grades.t3>=0)) { fwrite(&grades, sizeof(grades), 1, fpout); // this will write the ENTIRE structure called grades so that all 3 scores // will be written printf("\nEnter the 3 test scores separated by spaces. Enter 3 negative numbers if done "); scanf("%d %d %d" &grades.t1, &grades.t2, &grades.t3); // get 3 more test scores } fclose(fpout); return (0); } To input a file, you can use the feof function so that you will know when you have reached the end of the file. You have to be very careful using it, though. If you read a record and it is the LAST record the end-of-file indicator was not set. If you try to read the file AGAIN without testing for the end of the file, you will have an error. The above example using structures and the fread instruction to input a file would look like the following: // input3.cpp // This program will read test scores from a disk file. It assumes that each student has 3 test scores // Each time the program tries to read 3 scores. If it is ever unsuccessful in doing that it will quit // The data will be input from a standard text file into a data structure called grades #include <stdio.h> struct InRec { int t1, t2, t3; } int main()

{ struct InRec grades; //set up a structure called grades to hold the 3 test scores FILE *fpin; // set up the file pointer to use for the output file fpin=fopen("a:grades.dat","rb"); //open a file named grades.dat as a binary file // to input from on the floppy disk if(fpin = =NULL) // make sure that you can read the disk, it may not be in the drive or // the disk might be damaged, or the file may not be on the disk { printf("\nFor some reason the file grades.dat could not be opened on the A: drive"); exit(0); // and quit the program } fread(&grades, sizeof(grades),1, fpin); //go ahead and read the first 3 grades while ( !feof(fpin) ) // while you were successful in reading a record { printf("\n t1= %d, t2= %d, t3= %d", grades.t1, grades.t2, grades.t3); fread(&grades, sizeof(grades),1, fpin); //read the next 3 grades } fclose(fpin); return (0); } Another example //This program will create a file from structures input by the user //The file will be opened as a "wb" write-binary file so that // output can be made directly from the structure in memory. //You will NOT be able to // "look" at this file because it is a binary file #include <stdio.h> #include <conio.h> // want to use getche() #include <stdlib.h> //want to use the exit() function #include <ctype.h> //want to use toupper() to convert // a character to uppercase struct EMPL {char name[10]; //first name only int age; }; int main( ) { char answer; //used to hold the input characters FILE *fp; //allocate storage for one file pointer struct EMPL student; 1. fp=fopen("students.dat","wb");//open the file "students.dat" on

//the a: // drive as a "write binary"file if ( fp==NULL) // if for some reason the file could not be { printf("\nThe file could not be opened"); // opened exit(0); //quit the program! } printf("\nDo you have more students to enter(Y/N)"); answer=getche(); while (toupper(answer)=='Y') { printf("\nEnter student's first name and age separated by a space: " ); scanf("%s %d",student.name, &student.age); fwrite(&student,sizeof(student),1,fp); flushall(); //get rid of any extraneous characters in the buffer printf("\nDo you have more students to enter(Y/N)"); answer=getche(); } fclose(fp); //good programmers close their files return 0; }

The below program will read the binary file created by the program above // This program will read a file and input to structures //The file will be opened as a "rb" read-binary file so that // input can // be made directly into the structure in memory. #include <stdio.h> #include <conio.h> #include <stdlib.h> // want to use getche() //want to use the exit() function

struct EMPL {char name[10]; //first name only int age; }; int main( ) { char answer; //used to hold the input characters FILE *fp; //allocate storage for one file pointer struct EMPL student; fp=fopen("students.dat","rb"); //open the file "students.dat" on //the a: // drive as a "read binary"file if ( fp==NULL) // if for some reason the file could not be

printf("\nThe file could not be opened"); // opened exit(0); //quit the program!

} fread(&student,sizeof(student),1,fp); while (!feof(fp)) //while there are still records to read { printf("\nThe student is %s and his/her age is %d", student.name,student.age); fread(&student,sizeof(student),1,fp); } fclose(fp); return 0; } //good programmers close their files

Вам также может понравиться