Download presentation
Presentation is loading. Please wait.
Published byAvis Pierce Modified over 8 years ago
1
PHY 107 – Programming For Science
2
Today’s Goal Get familiar with opening & closing files Declaring variables for use with files Using variables to open files for reading & writing Closing files and understand why you should do so ALL Understand what it means: ALL I/O is file I/O Common bugs to avoid when using files in C/C++ Get a better understanding of scanf & printf Files as variables: know what their types are
3
Image To Sharpen I have a (fuzzy) 1024 x 768 picture to sharpen 786,432 Only 786,432 numbers to type in to yesterday's lab Will also need to click each pixel to update with result
4
More Data Entry Positions Testing improved jet designs for oeingB-ay Using program to simulate designs' lift & drag 5 possible designs (each 150MB) to test this iteration Once results available, will tweak & retest designs Need room of touch typists for all this data entry
5
This Is (Semi-Real) Problem Large hadron collider eventually work as designed No black hole when smashing particles at high speeds 28.5 GB/min Creates 28.5 GB/min for nerds seeking truth & beauty
6
This Is (Semi-Real) Problem Large hadron collider eventually work as designed No black hole when smashing particles at high speeds 28.5 GB/min Creates 28.5 GB/min for nerds seeking truth & beauty Hired trained monkeys to type all 244,813,135,872 bits
7
This Is (Semi-Real) Problem Large hadron collider eventually work as designed No black hole when smashing particles at high speeds 28.5 GB/min Creates 28.5 GB/min for nerds seeking truth & beauty Hired trained monkeys to type all 244,813,135,872 bits college students
8
Yeah, Right Real world demands we use files for most I/O Data files used to start and/or end most projects May contain: game levels, analysis results, CCD pics Way to read & write files needed to be useful
9
Opening a File To use file, we need variable to use in program Numbers, cStrings, and booleans mixed in the file Previous type (& arrays) do not make sense to use C provides new types to refer to file itself
10
Types Used For Files Within program, may use file in 2 possible ways To read file, pointer to FILE will be needed Also need variable of type FILE* to write to a file
11
File Variable Declaration Types are new, but still just declaring variables Requires type & name of variable being declared Names for human use; normal scoping rules apply Cannot assign variables Cannot assign variables but can use as parameters files are NOT numbers Cannot use in equations: files are NOT numbers FILE* fout; FILE* fin; FILE* bob, *bobBob, *bobBobBob, *bobJr; FILE* thisIsAFileVariable; FILE* monkey = "foo.txt"; FILE *fourFile = 4;
12
File Variable Declaration Types are new, but still just declaring variables Requires type & name of variable being declared Names for human use; normal scoping rules apply Cannot assign variables Cannot assign variables but can use as parameters files are NOT numbers Cannot use in equations: files are NOT numbers FILE* fout; FILE* fin; FILE* bob, *bobBob, *bobBobBob, *bobJr; FILE* thisIsAFileVariable; FILE* monkey = "foo.txt"; FILE *fourFile = 4;
13
File Variable Declaration Types are new, but still just declaring variables Requires type & name of variable being declared Names for human use; normal scoping rules apply Cannot assign variables Cannot assign variables but can use as parameters files are NOT numbers Cannot use in equations: files are NOT numbers FILE* fout; FILE* fin; FILE* bob, *bobBob, *bobBobBob, *bobJr; FILE* thisIsAFileVariable; FILE* monkey = "foo.txt"; FILE *fourFile = 4;
14
Name That File Two ways to open a file once we have the name No matter which used, must know name of file Defaults to current directory, if only a name specified By including in name, can use other directories No standard way to do this – depends on the OS
15
Name That File Two ways to open a file once we have the name No matter which used, must know name of file Defaults to current directory, if only a name specified By including in name, can use other directories No standard way to do this – depends on the OS
16
Opening the File Can open file when variable declared char nameLoc[] = "bobbobbob"; char sndName[] = "csi.txt"; FILE* fin = fopen("image.dat”,”r”); FILE* fout = fopen("image.dat”,”w”); FILE* bobism = fopen(nameLoc,”a”); FILE* cookies = fopen(sndName,”r+”); Even after declaration, files can be opened FILE* because; FILE* isaidso; because = fopen("mightMakes.right”,”r”); scanf(“%s”, sndName); isaidso = fopen(sndName,”w”);
17
Did I Do Good? May not always be successful opening a file Cannot open and read file that does not exist May not have permission to access a certain file Cannot do impossible & write to nonexistent drive NULL pointer returned if fopen did not work If call succeeded, then will have variable != NULL variable == NULL when attempt to open file fails May not work before calling fopen or after fclose
18
Did I Do Good? May not always be successful opening a file Cannot open and read file that does not exist May not have permission to access a certain file Cannot do impossible & write to nonexistent drive NULL pointer returned if fopen did not work If call succeeded, then will have variable != NULL variable == NULL when attempt to open file fails May not work before fopen or after fclose
19
Examples Of How NULL Works char sndName[]; FILE *because, *foo=fopen(”f.txt”,”r”); FILE *isaidso, *bar=fopen(”snafu”,”w”); isaidso = NULL; printf(“%p\n”,because); printf(“%p\n”,foo); printf(“%p\n”,bar); printf(“%p\n”, isaidso); because=fopen(”doesNotExist.txt”,”r”); isaidso=fopen(”doesNotExist.txt”,”w”); printf(“%p\n”, because); printf(“%p\n”, isaidso);
20
Examples Of How NULL Works char sndName[]; FILE *because, *foo=fopen(”f.txt”,”r”); FILE *isaidso, *bar=fopen(”snafu”,”w”); isaidso = NULL; printf(“%p\n”,because); printf(“%p\n”,foo); printf(“%p\n”,bar); printf(“%p\n”, isaidso); because=fopen(”doesNotExist.txt”,”r”); isaidso=fopen(”doesNotExist.txt”,”w”); printf(“%p\n”, because); printf(“%p\n”, isaidso);
21
Upon Opening The Location Is… Once open, read & write from start of file As logical a choice as any other location to start at If reading, can start getting all data from file When writing to existing file what will happen?
22
Oops!
23
Opening a File Within program, may use file in 2 possible ways Reading data from a file that already exists Create or erase (as appropriate) & write file from scratch
24
Opening a File 3
25
Closing File Important to close files once you are done Program will delay saving data to make it faster Crashes cause data loss if saves had been waiting Until file is closed may be locked from other uses Immediately saved on close, so insures data is safe Can open more files if limit of open files reached FILE* mets = fopen(”nlChamp.txt”,”r”); FILE* yankees = fopen(”evil.txt”,”a”); fclose(mets); fclose(yankees);
26
Today's Key Point Because of its history, all C/C++ I/O is file based Obvious when file is source of data or target of write But also true when reading from keyboard Writing to screen also considered file I/O
27
Today's Key Point
28
What Are printf & scanf ? To use printf & scanf we also need: #include
29
What Are printf & scanf ? To use printf & scanf we also need: #include Include statement needed for file I/O #include
30
What Are printf & scanf ? To use printf & scanf we also need: #include Include statement needed for file I/O #include There is a reason: this is not an accident printf & scanf are special versions of file I/O functions
31
Deep in Bowels of stdio.h In stdio.h find 2 functions included in code: int printf( ) { fprintf(stdout, ); } int scanf( ) { fscanf(stdin, ); } Already written code reading/writing from a file Now must specify FILE* variable & not be as lazy
32
Input Using scanf
33
Input Using fscanf and FILE*
34
Output using printf Already seen how to print text using printf printf(“Hello World\n”); Prints out whatever is placed between quotes Print variables’ values with specifier and adding after Use escape sequences for fancier text output \n newline (move to start of next line) \t tab (go to next column that is multiple of 8) \\ \ (backslash character) \” “ (quotation mark)
35
Output using fprintf & FILE* File output easy to write text using fprintf FILE * fOut = fopen(fileName, “w”); fprintf(fOut,“Hello World\n”); Prints out whatever is placed between quotes Print variables’ values with specifier and adding after Use escape sequences for fancier text output \n newline (move to start of next line) \t tab (go to next column that is multiple of 8) \\ \ (backslash character) \” “ (quotation mark)
36
See How Easy It Is? #include #include int main(void) { int sum = 0; int val; printf("-1 to quit or sum nums typed\n”); scanf(“%d”,&val); while (val != -1) { sum += val; printf(”%d\n”, val); scanf(“%d”,&val); } return 0; }
37
See How Easy It Is? #include #include int main(void) { FILE* fin; FILE* fout; int sum = 0; int val; fprintf(fout,"-1 to quit or sum nums typed\n”); fscanf(fin,“%d”,&val); while (val != -1) { sum += val; fprintf(fout,”%d\n”, val); fscanf(fin, “%d”,&val); } return 0; }
38
And When We Run It? #include #include int main(void) { FILE* fin; FILE* fout; int sum = 0; int val; fprintf(fout,"-1 to quit or sum nums typed\n”); fscanf(fin,“%d”,&val); while (val != -1) { sum += val; fprintf(fout,”%d\n”, val); fscanf(fin, “%d”,&val); } return 0; }
39
And When We Run It?
40
Must Open File Before Using How file opened unimportant, just that is open Open when declared, by assigning in declaration FILE* bobIn=fopen("file.txt","r"); FILE* whyNot=fopen(strFromUser,"w"); Open later in program using same fopen() call bobIn=fopen("file.txt","r"); whyNot=fopen(strFromUser,"w"); Variable must refer to open file or else it crashes Often add need to use NULL to protect from crashs
41
See How Easy It Is? #include #include int main(void) { int sum = 0; int val; printf("-1 to quit or sum nums typed\n”); scanf(“%d”,&val); while (val != -1) { sum += val; printf(”%d\n”, val); scanf(“%d”,&val); } return 0; }
42
See How Easy It Is? #include #include int main(void) { FILE* fin = fopen(“input.dat”,”r”); FILE* fout = fopen(“results.csv”,”w”); if (fin != NULL && fout != NULL) { int sum = 0; int val; fprintf(fout,"-1 to quit or sum nums typed\n”); fscanf(fin,“%d”,&val); while (val != -1) { sum += val; fprintf(fout,”%d\n”, val); fscanf(fin, “%d”,&val); } } return 0; }
43
See How Easy It Is? #include #include int main(void) { FILE* fin = fopen(“input.dat”,”r”); FILE* fout = fopen(“results.csv”,”w”); if (fin != NULL && fout != NULL) { int sum = 0; int val; printf("-1 to quit or sum nums typed\n”); fscanf(fin,“%d”,&val); while (val != -1) { sum += val; fprintf(fout,”%d\n”, val); fscanf(fin, “%d”,&val); } } return 0; }
44
Variables are Variables Like all variables, can use files as parameters Argument must also be file variable for it to compile Reading & writing continues through the function Can only go forward in file no matter what Within the function, "file position marker" continues Cannot unring bell, does not overwrite file on return As with scanf, will not reread after function
45
But… Like all variables, can use files as parameters Argument must also be file variable for it to compile Reading & writing continues through the function Can only go forward in file no matter what Within the function, "file position marker" continues Cannot unring bell, does not overwrite file on return As with scanf, will not reread after function
46
But… Like all variables, can use files as parameters Argument must also be file variable for it to compile Reading & writing continues through the function Can only go forward in file no matter what Within the function, "file position marker" continues Cannot unring bell, does not overwrite file on return As with cin to read, will not reread after function
47
Butt… Like all variables, can use files as parameters Argument must also be file variable for it to compile Reading & writing continues through the function Can only go forward in file no matter what Within the function, "file position marker" continues Cannot unring bell, does not overwrite file on return As with cin to read, will not reread after function
48
Variables are Variables Like all variables, can use files as parameters Argument must also be file variable for it to compile Reading & writing continues through the function Can only go forward in file no matter what Within the function, "file position marker" continues Cannot unring bell, does not overwrite file on return As with scanf, will not reread after function PARAMETER MUST BE PASS-BY-REFERENCE
49
Your Turn Get into your groups and try this assignment
50
For Next Lecture Another use of data files on pages 197 - 204 Must we use text or are there faster approaches? What was the point of learning binary numbers? Could we predict size of file we read/write in program? Weekly Assignment available tomorrow Due next Tuesday; break from assignments over Programming Assignment #3 available Friday
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.