PHY 107 – Programming For Science. Today’s Goal  Get familiar with opening & closing files  Declaring variables for use with files  Using variables.

Slides:



Advertisements
Similar presentations
BITS Pilani, Pilani Campus TA C252 Computer Programming - II Vikas Singh File Handling.
Advertisements

Chapter 11: Data Files & File Processing In this chapter, you will learn about Files and streams Creating a sequential access file Reading data from a.
FILES Files types and operations. Files Files are used to store data Data can be Text (ASCII only: 0  127) Binary (Full range: 0  256) Each file resides.
1 ICS103 Programming in C Lecture 8: Data Files. 2 Outline Why data files? Declaring FILE pointer variables Opening data files for input/output Scanning.
1 ICS103 Programming in C Lecture 3: Introduction to C (2)
Guide To UNIX Using Linux Third Edition
Console and File I/O - Basics Rudra Dutta CSC Spring 2007, Section 001.
Chapter 18 I/O in C. Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Standard C Library I/O commands.
© Janice Regan, CMPT 128, Jan CMPT 128: Introduction to Computing Science for Engineering Students C File Input and Output Checking input for errors.
CSC 107 – Programming For Science. Today’s Goal  Learn how arrays normally used in real programs  Why a function returning an array causes bugs  How.
C Programming Lecture 3. The Three Stages of Compiling a Program b The preprocessor is invoked The source code is modified b The compiler itself is invoked.
CSC 107 – Programming For Science. Today’s Goal ALL  Understand why ALL I/O is file I/O  Common bugs to avoid when coding with files in C++  Get a.
Files COP3275 – PROGRAMMING USING C DIEGO J. RIVERA-GUTIERREZ.
CSC 213 – Large Scale Programming. Project #1 Recap.
1 CS 101 Lecture 2. 2 Input from the Keyboard Here is a program to accept input from the keyboard and put into into two variables. #include main(){ cout.
CSC 107 – Programming For Science. Announcements  Memorization is not important, but…  … you will all still be responsible for information  Instead.
CSC 107 – Programming For Science. Today’s Goal  Get familiar with opening & closing files  Declaring variables for use with files  Using variables.
1 File Handling. 2 Storage seen so far All variables stored in memory Problem: the contents of memory are wiped out when the computer is powered off Example:
CSC 107 – Programming For Science. Announcements.
Chapter 11: Data Files and File Processing Files and streams Creating a sequential access file Reading data from a sequential access file Using fgetc()
Chapter 12 Files (reference: Deitel ’ s chap 11) chap8.
PHY 107 – Programming For Science. The Week’s Goal.
© Janice Regan, CMPT 102, Sept CMPT 102 Introduction to Scientific Computer Programming Input and Output.
PHY 107 – Programming For Science. Today’s Goal  Learn how arrays normally used in real programs  Why a function returning an array causes bugs  How.
CSC 107 – Programming For Science. Today’s Goal  Get familiar with opening & closing files  Declaring variables for use with files  Using variables.
PHY 107 – Programming For Science. Today’s Goal  Discuss how to hand data to functions  Review loopholes in variables & scoping rules  Ways to get.
CSC Programming for Science Lecture 18: More Data Files.
Sudeshna Sarkar, IIT Kharagpur 1 Programming and Data Structure Sudeshna Sarkar Lecture 3.
PHY 107 – Programming For Science. Final Exam  Wed., Dec. 16 th from 2:45PM – 4:45PM in OM110  For exam, plan on using full 2 hours  If major problem,
Hank Childs, University of Oregon
Chapter 1.2 Introduction to C++ Programming
Chapter 1.2 Introduction to C++ Programming
CSE 220 – C Programming C Fundamentals.
A bit of C programming Lecture 3 Uli Raich.
Chapter 2 - Introduction to C Programming
Chapter 22 – part a Stream refer to any source of input or any destination for output. Many small programs, obtain all their input from one stream usually.
TMF1414 Introduction to Programming
University of Washington Computer Programming I
ICS103 Programming in C Lecture 3: Introduction to C (2)
Chapter 18 I/O in C.
Getting Started with C.
Lecture 13 & 14.
Chapter 2 - Introduction to C Programming
MATLAB: Structures and File I/O
Programming in C Input / Output.
Files I/O, Streams, I/O Redirection, Reading with fscanf
Hank Childs, University of Oregon
Chapter 2 - Introduction to C Programming
Chapter 2 - Introduction to C Programming
Chapter 2 - Introduction to C Programming
Chapter 18 I/O in C.
Introduction to Primitive Data types
File I/O in C Lecture 7 Narrator: Lecture 7: File I/O in C.
File Input and Output.
File Handling.
Chapter 2 - Introduction to C Programming
Accessing Files in C Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition,
Fundamental of Programming (C)
C Programming Getting started Variables Basic C operators Conditionals
Functions continued.
Chapter 2 - Introduction to C Programming
EPSII 59:006 Spring 2004.
Strings …again.
Introduction to C Programming
Chapter 11 Files chap8.
EECE.2160 ECE Application Programming
ICS103: Programming in C 6: Pointers and Modular Programming
Introduction to Primitive Data types
Files Chapter 8.
Presentation transcript:

PHY 107 – Programming For Science

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

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

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

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

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

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

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

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

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

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;

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;

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;

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

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

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”);

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

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

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);

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);

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?

Oops!

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

Opening a File 3

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);

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

Today's Key Point

What Are printf & scanf ?  To use printf & scanf we also need: #include

What Are printf & scanf ?  To use printf & scanf we also need: #include  Include statement needed for file I/O #include

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

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

Input Using scanf

Input Using fscanf and FILE*

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)

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)

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; }

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; }

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; }

And When We Run It?

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

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; }

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; }

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; }

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

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

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

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

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

Your Turn  Get into your groups and try this assignment

For Next Lecture  Another use of data files on pages  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