REACH CECS 130 Exam 2 Test Review
This resource provides a comprehensive review of file input/output operations in C, focusing on functions such as fopen, fclose, fscanf, and fprintf. It includes examples of reading from and writing to files, handling data with unions, and utilizing C's standard library for file operations. Learn how to properly manage file pointers and handle errors when opening files. The document also covers practical programming exercises to implement and reinforce these concepts, making it an essential guide for students and developers looking to enhance their C programming skills.
REACH CECS 130 Exam 2 Test Review
E N D
Presentation Transcript
C - Files Do you know the syntax for each of these, used to read and write to data files? • Pointers: think of it as the memory address of the file • fopen() • fclose() • fscanf() • fprintf()
Union Output: 9 3.1416 #include <stdio.h> #include<stdlib.h> union NumericType { int iValue; long lValue; double dValue; }; int main() { union NumericType Values; // iValue = 10 Values.iValue=9; printf("%d\n", Values.iValue); Values.dValue = 3.1416; printf("%f\n", Values.dValue); system("pause"); }
fopen(“file name”, “Mode”) • fopen() returns a FILE pointer back to the pRead variable • #include <cstdio> • Main() • { • FILE *pRead; • pRead = fopen(“file1.dat”, “r”); • if(pRead == NULL) • printf(“\nFile cannot be opened\n”); • else • printf(“\nFile opened for reading\n”); • fclose(pRead); • }
What does this code do? int main () { FILE * pFile; char c; pFile=fopen("alphabet.txt","wt"); for (c = 'A' ; c <= 'Z' ; c++) { putc (c , pFile);//works like fprintf } fclose (pFile); return 0; }
fclose(file pointer) • Pretty basic. • Always close files when you use fopen.
fscanf(FILE pointer, “data type”, variable in which to store the value) • Reads a single field from a data file • “%s” will read a series of characters until a white space is found • can do fscanf(pRead, “%s%s”, name, hobby);
#include <stdio.h> • Main() • { • FILE *pRead; • char name[10]; • pRead = fopen(“names.dat”, “r”); • if( pRead == NULL ) • printf( “\nFile cannot be opened\n”); • else • printf(“\nContents of names.dat\n”); • fscanf( pRead, “%s”, name ); • while( !feof(pRead) ) { // While end of file not reached • printf( “%s\n”, name ); // output content of name • fscanf( pRead, “%s”, name ); // scan from file next string • } • fclose(pRead); • }
Quiz Kelly 11/12/86 6 Louisville Allen 04/05/77 49 Atlanta Chelsea 03/30/90 12 Charleston Can you write a program that prints out the contents of this information.dat file?
#include <stdio.h> • Main() • { • FILE *pRead; • char name[10]; • char birthdate[9]; • float number; • char hometown[20]; • pRead = fopen(“information.dat”, “r”); • if( pRead == NULL ) • printf( “\nFile cannot be opened\n”); • else • fscanf( pRead, “%s%s%f%s”, name, birthdate, &number, hometown ); • while( !feof(pRead) ) { • printf( “%s \t %s \t %f \t %s\n”, name, birthdate, number, hometown ); • fscanf( pRead, “%s%s%f%s”, name, birthdate, &number, hometown ); • } • fclose(pRead); • }
fprintf(FILE pointer, “list of data types”,list of values or variables) • The fprintf() function sends information (the arguments) according to the specified format to the file indicated by stream. fprintf() works just like printf() as far as the format goes.
#include <stdio.h> Main() { FILE *pWrite; char fName[20]; char lName [20]; float gpa; pWrite = fopen(“students.dat”,”w”); if( pWrite == NULL ) printf(“\nFile not opened\n”); else printf(“\nEnter first name, last name, and GPA ”); printf(“separated by spaces:”); scanf(“%s%s%f”, fName, lName, &gpa); fprintf(pWrite, “%s \t %s \t % .2f \n”, fName, lName, gpa); fclose(pWrite); }
Quiz • Can you write a program that asks the user for their • Name • Phone Number • Bank account balance And then prints this information to a data file called accounts.dat ?
C++ Input/Output • Summary • Include #include <iostream> directive at beginning of program • Use cin to take data from user • Use cout to display data on screen • Display multiple strings and integers in the same cout statement by separating items with <<
C++ Input/Output Example #include <iostream> #include<string> using namespace std; string name = “”; int main(void) { cout<<“What is your name?”; cin>>name; cout<<endl<<“Hello”<<name.c_str(); return 0; }
Can you predict the printout? #include <iostream> using namespace std; int x = 25; string str2 = “This is a test”; int main( void ) { cout<<“Test”<<1<<2<<“3”; cout<<25 %7<<endl<<str2.c_str(); return 0; }
Answer Test 1234 This is a test
Data • How a computer stores data in its internal memory • RAM (Random-Access Memory) - temporary • ROM (Read-Only Memory) – non volatile • Store data in bytes • How you store data temporarily • Create variables based on fundamental types (bool, char, int, float) • constants: #define CONSTNAME value • sizeof()
Control Statements – Boolean Operators • What do each of the following evaluate to? 1. long elves = 8; int dwarves = 8; if(elves==dwarves) //true or false? if(elves!=0) //true or false? 2. int elves = 4; int dwarves = 5; if(dwarves > (2/3)) //true or false? 3. if(0 < x < 99) //true or false? 4. if(0<= (0<1))//true or false?
Control Statements – Boolean Operators -Answers • What do each of the following evaluate to? 1. long elves = 8; int dwarves = 8; if(elves==dwarves) //true if(elves!=0) //true 2. int elves = 4; int dwarves = 5; if(dwarves > (2/3)) //true 3. if(0 < x < 99) //true …TRUE (1) and FALSE (0) < 99 4. if(0<= (0<1))//true
If statements • if(condition) statement; else if (condition) statement; • condition ? expr1 : expr2 • ex. z = ( x > y ) ? y : x ; • Can we do next statement? (x>y) ? cout << “x is greater than y.” : cout << “x isn’t greater than y.”;
Switch-case statements switch(expression){ case expr1: statement; break; case expr2: statement; break; case expr3: statement; break; default: statements break; }
Loops • while (condition) { statements; You need to maintain a state to break loop. } • do { statements; You need to maintain a state to break loop. } while(condition);
Loops • for (initialization; condition; expression) { statements; } • Incrementing: Prefix and Postfix int x = 5; int y = 6; int z = y++ //z=6, y=7 postfix operator int z = ++x //z=6, x=6 prefix operator
FOR LOOP TEST • Can you write a program that prints out the following? 0 1 2 3 4 5 6 7 8 9
Answer for ( int count = 0; count < 10; count ++) { cout <<count<<“”; }
Other Challenge questions for Loops • Write a conditional statement that will assign x/y to x if y doesn’t equal 0. • Write a while loop that calculates the summative of positive integers from 1 to some number n. • Write a conditional statement that assigns x*y if x is even; otherwise , if x is odd and y doesn’t equal 0, assign x to x/y; if neither of the preceding cases is true, output to the screen that y is equal to 0.
How to declare and implement functions • Function declaration • Function definition • Function call
#include <iostream> using namespace std; int add(int a, int b); int main(void) { int number1, number2; cout << “Enter the first value to be summed:”; cin >> number1; cout << “\nEnter the second:”; cin >> number2; cout << “\n The sum is: “ << add (number1, number2) <<endl; } int add(int a, int b) { return a+b; }
Functions Challenge • Write a function, called multiply that multiplies two numbers and returns the result
OOP • Declare classes • Create objects • 3 MAIN PRINCIPLES OF OOP • Data abstraction – hiding data members and implementation of a class behind an interface so that the user of the class corrupt that data • Encapsulation – each class represents a specific thing or concept. Multiple classes combine to produce the whole • Polymorphism-objects can be used in more than one program
Classes • Classes are general models from which you can create objects • Classes have data members either data types or methods • Classes should contain a constructor method and a destructor method • See handout for example of a program that utilizes a class
Declaring Classes class ClassName { memberList }; memberList can be either data member declarations or method declarations
Class Declaration Example Class Bow { //data member declarations string color; bool drawn; intnumOfArrows; Bow(string aColor); //constructor ~Bow(); //destructor //methods void draw(); int fire(); };
Creating Methods Return_type ClassName::methodName(argumentList) { methodImplementation }
Methods Creation Example //draws the bow Void Bow::draw() { drawn = true; cout<< “The “<<color<<“bow has been drawn.”<<endl; }
Advanced Data Types • Arrays • Pointers
How to create arrays • data_typearray_name [number-of-elements]; • Two Dimensional Array array_typearray_name [number_of_ROWS][number_of_COLUMNS];
How to create pointers • type* pointer_name; • ex. int my_int; int* my_int_pointer = &my_int; Assigns the address of my_int to the pointer
Useful string functions • Copying strings from one to another • char* strcpy(char* p, const char* q); • char s[6]; strcpy(s, “Hello”); • To combine strings • char* strcat(char* p, const char* q); • char s[12] = “Hello” strcat(s, “World”);
Useful string functions • To copy n characters from q to the of p. • char* strncpy(char* p, const char* q, int n); • char s [7] = “Say “; char t[] = “Hi”; strncpy (s, t, 2)
Challenge question • Can you write a program using C++ that uses a FOR loop to initialize a 2D array that looks like the following {0,5,10,15}{0,2,4,6}
Answer #include<iostream> using namespace std; int main(){ int array[2][4], , row, column; for(row=0;row<2;row++) for(column=0;column<4;column++){ if(row==0) array[row][column]=column*5; else if(row==1) array[row][column]=column*2; } for(row=0; row<2; row++){ for(column =0; column <4; column ++) cout<<array[row][column]<<" "; cout<<endl; } system("pause"); return 0; }
Basics of C++ • Basic framework for a program • How to Comment • How to Print • How to store variables • How to Print stored variables • How to find the size of a variable • How to convert from one data type to another • How to Declare Constants
Basics of C++ • If statements • Conventional • Using conditional operator • Switch-case statements • Loops • While • Do-While • For • Branching statements
Basics of C++ • How to declare and implement functions • How to create arrays • How to create pointers • Useful string functions • Classes
How to Comment • //this is how you comment • /*this is how you comment */ Use for Multiple lines