C File Processing - I Math 130 B Smith: Eval: 3. Energy and excitement helped for avg graphics. Gen interest. A bit wordy, henced redundant in some parts.

Slides:



Advertisements
Similar presentations
File Management in C. What is a File? A file is a collection of related data that a computers treats as a single unit. Computers store files to secondary.
Advertisements

BITS Pilani, Pilani Campus TA C252 Computer Programming - II Vikas Singh File Handling.
File Management in C. A file is a collection of related data that a computers treats as a single unit. File is a collection of data stored permanently.
Files in C Rohit Khokher. Files in C Real life situations involve large volume of data and in such cases, the console oriented I/O operations pose two.
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.
KUKUM Sem2-05/06EKT120: Computer Programming1 Week 11 – Files.
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.
CSCI 171 Presentation 12 Files. Working with files File Streams – sequence of data that is connected with a specific file –Text Stream – Made up of lines.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Introduction Data files –Can be created, updated,
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.
 2007 Pearson Education, Inc. All rights reserved C File Processing.
Chapter 11 C File Processing Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
Guide To UNIX Using Linux Third Edition
V-1 University of Washington Computer Programming I File Input/Output © 2000 UW CSE.
Chapter 18 I/O in C. Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Standard C Library I/O commands.
Lecture 11 – Files Operation. Introduction Almost all of the program developed before this is interactive In interactive environment, input is via keyboard.
© Janice Regan, CMPT 128, Jan CMPT 128: Introduction to Computing Science for Engineering Students C File Input and Output Checking input for errors.
1 Homework Introduction to HW7 –Complexity similar to HW6 –Don’t wait until last minute to start on it File Access will be needed in HW8.
A First Book of ANSI C Fourth Edition Chapter 10 Data Files.
Lone Leth Thomsen Input / Output and Files. April 2006Basis-C-8/LL2 sprintf() and sscanf() The functions sprintf() and sscanf() are string versions of.
Chapter 9 I/O Streams and Data Files
1. Introduction File Declaration and Initialization Creating and Opening File Closing File EOF Reading from and Writing into a File Extra : Random Access.
Introduction to Programming Using C Files. 2 Contents Files Working with files Sequential files Records.
File IO and command line input CSE 2451 Rong Shi.
Chapter 8 File-Oriented Input and Output. 8.1 INTRODUCTION a file can also be designed to store data. We can easily update files, A data file as input.
CSEB114: Principle of programming Chapter 11: Data Files & File Processing.
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:
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 7 : File Processing1 File-Oriented Input & Output CHAPTER 7.
1 CHAPTER6 CHAPTER 6. Objectives: You’ll learn about;  Introduction  Files and streams  Creating a sequential access file  Reading data from a sequential.
Lecture 11: Files & Arrays B Burlingame 18 November 2015.
CNG 140 C Programming (Lecture set 10) Spring Chapter 10 Data Files.
24-2 Perform File I/O using file pointers FILE * data-type Opening and closing files Character Input and Output String Input and Output Related Chapter:
chap8 Chapter 12 Files (reference: Deitel ’ s chap 11)
GAME203 – C Files stdio.h C standard Input/Output “getchar()”
Files A collection of related data treated as a unit. Two types Text
Files. FILE * u In C, we use a FILE * data type to access files. u FILE * is defined in /usr/include/stdio.h u An example: #include int main() { FILE.
UniMAP Sem2-09/10 DKT121: Fundamental of Computer Programming1 Files Operations.
Lecture 20: C File Processing. Why Using Files? Storage of data in variables and arrays is temporary Data lost when a program terminates. Files are used.
1 Computer Programming Lecture 15 Text File I/O Assist. Prof Dr. Nükhet ÖZBEK Ege University Department of Electrical&Electronics Engineering
Connecting to Files In order to read or write to a file, we need to make a connection to it. There are several functions for doing this. fopen() – makes.
C Programming Day 2. 2 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Union –mechanism to create user defined data types.
UniMAP SemI-11/12EKT120: Computer Programming1 Files.
UniMAP SemI-11/12EKT120: Computer Programming1 Files.
DKT121: Fundamental of Computer Programming
ECE Application 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.
ECE Application Programming
EKT120: Computer Programming
File Access (7.5) CSE 2031 Fall July 2018.
Chapter 18 I/O in C.
File I/O.
Plan for the Day: I/O (beyond scanf and printf)
CSE1320 Files in C Dr. Sajib Datta
File Input/Output.
Programming in C Input / Output.
Files I/O, Streams, I/O Redirection, Reading with fscanf
Beginning C Lecture 11 Lecturer: Dr. Zhao Qinpei
File I/O in C Lecture 7 Narrator: Lecture 7: File I/O in C.
File Input and Output.
File Handling.
File Access (7.5) CSE 2031 Fall January 2019.
File Access (7.5) CSE 2031 Fall February 2019.
Programming in C Input / Output.
File Handling in C.
A First Book of ANSI C Fourth Edition
EECE.2160 ECE Application Programming
Files Operations.
CSc 352 File I/O Saumya Debray Dept. of Computer Science
Files Chapter 8.
Presentation transcript:

C File Processing - I Math 130 B Smith: Eval: 3. Energy and excitement helped for avg graphics. Gen interest. A bit wordy, henced redundant in some parts since most is discussed. Good for handout, bad for lectures. B Smith: Eval: 3. Energy and excitement helped for avg graphics. Gen interest. A bit wordy, henced redundant in some parts since most is discussed. Good for handout, bad for lectures. B Smith: 4/13/2005 9:54 AM: Rate: 3, low discussion, implement, “Your turn…” Time: 50 minutes B Smith: 4/13/2005 9:54 AM: Rate: 3, low discussion, implement, “Your turn…” Time: 50 minutes B Smith: Rate:2/4 More examples needed, fewer words. B Smith: Rate:2/4 More examples needed, fewer words. B Smith: Sp06: rate 2.5 Worked mostly from examples 11.1 and Need better examples. B Smith: Sp06: rate 2.5 Worked mostly from examples 11.1 and Need better examples.

Overview C Functions to Open and Close Streams Declaring, Opening, and Closing Files Reading and Writing Files Example

Sharing Data Imagine 5 people around the world at terminals playing DOOM!  Central Game server Tracks games in session. Keeps record of players and status  How could we make our programs communicate?  Clearly, writing data, and reading data files is a possible solution!

Opening a File We have been working with programs that have  read from the “standard input” (the keyboard)  written to the “standard output” (the monitor) How can we access a file which is not already “connected” to the program? File processing is performed using a FILE structure/data- type. First you must declare an instance of the FILE structure. Examples: FILE* inFile; FILE* prices; FILE* fp; FILE* inFile; FILE* prices; FILE* fp; B Smith: In C a stream is referred to as a FILE. See attached notes. B Smith: In C a stream is referred to as a FILE. See attached notes.

Opening a File Files must be opened before they are worked with To open a file is to establish a link b/t your program, the OS, and the file An “open file” is one with which your program can communicate Analogous to taking the phone off the hook Helps preserve file integrity FILE represents a “stream”

Opening a File Use fopen() to open a file fopen() takes an external name such as “proj01.c” as an argument fopen() returns an internal file name for use in subsequent reads and writes to the file  this “handle” is a file pointer returned from fopen() //prototype FILE *fopen(char* FileName, char *Mode); FILE *fp; fp = fopen(“proj01.c”, “r”);

fopen() The file pointer returned from fopen() points to a file structure A file structure contains file details such as  buffer location  current character position in the buffer  whether the file is being read or written FILE *fp; fp = fopen(“proj01.c”, “r”);

fopen() The first argument of fopen is the name of the file, taken as a character string The second argument is the “mode,”  used to indicate how the file is to be used FILE *fp; fp = fopen(“proj01.c”, “r”);

fopen() The files opened by fopen() will generally be read, written, or appended  allowed modes reflect this mode r: read mode w: write mode a: append, or add to  file name and mode should be enclosed in double quotes FILE *fp; fp = fopen(“proj01.c”, “r”);

pgm 11.1 from Bronson textbook #include int main() { FILE *inFile; char fileName[13]; printf("\nEnter a file name: "); gets(fileName); inFile = fopen(fileName,"r"); /* open the file */ if (inFile == NULL) { printf("\nThe file cannot be opened."); printf("\nPlease check that the file currently exists."); exit(1); /* all open streams are closed */ } printf("\nThe file has been successfully opened for reading"); return 0; }

Opening a File for Writing: This creates a new file  makes the file available for output from the function opening the file  if a file with the same name exists, the old file is erased outFile = fopen(“prices.bnd”,”w”);

pgm 11.2 – Writing a File example #include int main() { int i; FILE *outFile; /* FILE declaration */ float price[] = {39.95,3.22,1.03}; /* a list of prices */ char *descrip[] = { "Batteries", /* a list of */ "Bulbs", /* descriptions */ "Fuses"}; outFile = fopen("prices.txt","w"); /* open the file */ if (outFile == NULL) { printf("\nFailed to open the file.\n"); exit(1); } for(i = 0; i < 3; ++i) fprintf(outFile,"%-9s %5.2f\n",descrip[i],price[i]); fclose(outFile); return 0; } system(“start notepad.exe prices.txt”); //to view file

Note File Size

Appending To a File This makes an existing file available for data to be added to end of file If the file opened for appending does not exist, a new file is created This new file is available to receive output from the program In append mode, data is written to the end of the file NB: in write mode, data is written starting at the beginning outFile = fopen(“prices.bnd”,”a”);

Reading from a file Open the file and save the returned pointer inFile = fopen(“sales.dat”,”r”); Check for existence of file  if (inFile == NULL)... requests to open a nonexistent file will return a NULL address Read the data using functions similar to scanf(), gets(), and getchar()

Bailing Out Errors should be communicated back to the OS  By convention, this is done with exit(1) or exit(0) Errors are also typically reported back to the user Conventionally, exit will return  a value of 0 for success  a nonzero value to indicate failue exit calls fclose for each open output file

Closing a File Use fclose() to close the files you’ve opened There is a limit to the maximum number of files you can have open Use the same internal pointer name to close the file Open files are normally closed automatically by the operating system upon exit

Writing to Files These functions are almost identical to those used for displaying to a monitor fputc(c, filename) Write a single character to a file fputs(string, filename) Write a string to the file fprintf(filename, “format”, args) Write the values of the arguments to the file according to the format string fputc(‘z’, outFile); Write a ‘z’ to the file fputs(“Nemo was a fish”, outFile) Write the string to the file fprintf(outFile, “%s %d”, descrip, price) B Smith: Not clear here what’s a proto and what’s a function example! B Smith: Not clear here what’s a proto and what’s a function example!

Writing a File How many characters are stored in prices.dat? How does this differ from the number mentioned in your textbook? Using a debugger, you can do a “dump” of prices.dat 51 characters can be found in prices.dat fclose() did not place a special end-of-file marker in the last item in the file B Smith: hidden B Smith: hidden

EOF EOF is not a special character that you retain in a variable It’s a constant (system dependent) that’s returned by various functions  scanf(), sscanf(), fscanf(), etc, in the event of an input failue EOF is also a valued returned by  getc(), getchar(), fgetc() in the event of a failure, or if no more characters are available to be read B Smith: move to end? B Smith: move to end?

Reading Files Very similar to reading data from the keyboard  all detect EOF.  fgetc() and fscanf() return EOF when the marker is detected  fgets() returns a NULL when it detects the end of a file fgetc(filename) Read a single character from the file fgets(stringname,n, filename) Read n-1 characters from the file and store in stringname fscanf(filename, “format”, &args) Read values for the listed arguments fgetc(infile); // Read the next character from the file fgets(message, 10, inFile) //Read file until: 9 characters, OR \n, OR EOF fscanf(inFile, “%f”, &price) //Read a floating point number

Reading data from a file #include int main() { char descrip[10]; float price; FILE *inFile; inFile = fopen("prices.txt","r"); if (inFile == NULL) { printf("\nFailed to open the file.\n"); exit(1); } while (fscanf(inFile,"%s %f",descrip,&price) != EOF){ printf("%-9s %5.2f\n",descrip,price); } fclose(inFile); return 0; } B Smith: Not a great example since it uses the same field names! The more logical thing to do would be to read a new file with fields chosen by the user! B Smith: Not a great example since it uses the same field names! The more logical thing to do would be to read a new file with fields chosen by the user!