GAME203 – C Files stdio.h C standard Input/Output “getchar()”

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

Week 5 Part I Kyle Dewey. Overview Exam will be back Thursday New office hour More on functions File I/O Project #2.
Files in C Rohit Khokher.
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.
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,
 2000 Prentice Hall, Inc. All rights reserved. Chapter 11 – File Processing Outline 11.1Introduction 11.2The Data Hierarchy 11.3Files and Streams 11.4Creating.
 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.
Chapter 9 Formatted Input/Output Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
Console and File I/O - Basics Rudra Dutta CSC Spring 2007, Section 001.
Files Programs and data are stored on disk in structures called files Examples Turbo C++ - binary file Word binary file lab1.c - text file lab1.data.
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.
Lone Leth Thomsen Input / Output and Files. April 2006Basis-C-8/LL2 sprintf() and sscanf() The functions sprintf() and sscanf() are string versions of.
File Handling Spring 2013Programming and Data Structure1.
22. FILE INPUT/OUTPUT. File Pointers and Streams Declarations of functions that perform file I/O appear in. Each function requires a file pointer as a.
File Handling In C By - AJAY SHARMA. We will learn about- FFile/Stream TText vs Binary Files FFILE Structure DDisk I/O function OOperations.
 2007 Pearson Education, Inc. All rights reserved C File Processing.
1 Lecture09: File I/O 5/6/2013 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
File IO and command line input CSE 2451 Rong Shi.
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:
1 Lecture09: File I/O 11/19/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
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 11 File Processing. Objectives In this chapter, you will learn: –To be able to create, read, write and update files. –To become familiar with.
 2000 Prentice Hall, Inc. All rights reserved Introduction Data files –Can be created, updated, and processed by C programs –Are used for permanent.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 11 – File Processing Outline 11.1Introduction.
Chapter 12 Files (reference: Deitel ’ s chap 11) chap8.
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.
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)
Files A collection of related data treated as a unit. Two types Text
 2007 Pearson Education, Inc. All rights reserved. 1 C File Processing.
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.
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.
 2007 Pearson Education, Inc. All rights reserved C File Processing.
Real Numbers Device driver process within the operating system that interacts with I/O controller logical record 1 logical record 2 logical record 3.
C Formatted Input/Output
RECURSION Recursion is a process where a function calls itself. main()
TMF1414 Introduction to Programming
File Access (7.5) CSE 2031 Fall July 2018.
File I/O.
Introduction to C CSE 2031 Fall /3/ :33 AM.
CSC215 Lecture Input and Output.
Plan for the Day: I/O (beyond scanf and printf)
CSE1320 Files in C Dr. Sajib Datta
CSE1320 Files in C Dr. Sajib Datta
Programming in C Input / Output.
What you need for the 1st phase of project
Files I/O, Streams, I/O Redirection, Reading with fscanf
CSE1320 Files in C Dr. Sajib Datta
Chapter 11 – File Processing
I/O in C Lecture 6 Winter Quarter Engineering H192 Winter 2005
Beginning C Lecture 11 Lecturer: Dr. Zhao Qinpei
Text and Binary File Processing
File Input and Output.
File Handling.
Fundamental of Programming (C)
Programming in C Input / Output.
File Handling in C.
EPSII 59:006 Spring 2004.
Module 12 Input and Output
File I/O.
Professor Jodi Neely-Ritz University of Florida
Presentation transcript:

GAME203 – C Files stdio.h C standard Input/Output “getchar()” “putchar(key)” EOF Redirection using “>” Redirection using “<”

Redirection Available in all OS's including DOS, Linux, Windows, MacOS Command line based “>” used to redirect output into a file (or device) “<” used to redirect input from a file (or device)

Advantages of Redirection No need for complicated code to choose file Can be run in a very flexible way using command line scripts Can replace user input with input from a file

Disadvantages of Redirection Need command line (or equivalent) Requires users that run the program to knopw about redirection

FILTER One of the most powerful little programs EVER You can Echo Substitute characters Double-space info Single-space info etc.....

Using PIPES (in Linux/MacOS) You can run this program that pipes (prints) the 2011 calendar out to the printer (lpr) device. $ cal 2011 | lpr where | is the PIPE symbol You can pipe it to “more” to direct it to screen $ cal 2011 | more The output of one program is the input of another program

FILES/DEVICES UNIX (& Linux/MacOS) allow for files and devices to look like the same thing /dev/ttyS0 or /dev/input/ttyS0 look like files but are really devices “ls -l” in a directory of devices (such as “/dev”) will show 2 types of devices (at least) CHARACTER and BLOCK

Programming with Devices Some devices are easy to access such as Standard input Standard output They have built-in functions to work with them “getchar( )” “putchar( key )” printf(“Hello World\n”);

Intro to File Handling One portable technique of working with files is using FILE POINTERS Use FILE *fp; // Create a pointer to a FILE struct fp = fopen( filename, filemode); // Opens a file as requested by // filemode

FILE MODE It can be: "r" Open a file for reading. The file must exist. "w" Create an empty file for writing. If a file with the same name already exists its content is erased and the file is treated as a new empty file. "a"Append to a file. Writing operations append data at the end of the file. The file is created if it does not exist. "r+" Open a file for update both reading and writing. The file must exist. "w+" Create an empty file for both reading and writing. If a file with the same name already exists its content is erased and the file is treated as a new empty file. "a+" Open a file for reading and appending. All writing operations are performed at the end of the file, protecting the previous content to be overwritten. You can reposition (fseek, rewind) the internal pointer to anywhere in the file for reading, but writing operations will move it back to the end of file. The file is created if it does not exist.

FILE NAMES Use string specifying either Absolute (specified from root “/”) Relative (specified from where you currently are) From home (specified from your home directory “~”)

Result of “fopen” Returns a POINTER NULL if it failed to open Pointer to a FILE struct if it succeeded Pointer is useful to allow subsequent operations to work! You must check to see it is valid before trying to perform other operations

File Open Example /* fopen example */ #include <stdio.h> int main () { FILE * pFile; pFile = fopen ("myfile.txt","w"); if (pFile!=NULL) fputs ("fopen example",pFile); fclose (pFile); } return 0;

getc int getc ( FILE * stream ); Get character from stream Returns the character currently pointed by the internal file position indicator of the specified stream. The internal file position indicator is then advanced by one character to point to the next character. getc is equivalent to fgetc and also expects a stream as parameter, but getc may be implemented as a macro, so the argument passed to it should not be an expression with potential side effects. See getchar for a similar function without stream parameter.

putc int putc ( int character, FILE * stream ); Write character to stream Writes a character to the stream and advances the position indicator. The character is written at the current position of the stream as indicated by the internal position indicator, which is then advanced one character. putc is equivalent to fputc and also expects a stream as parameter, but putc may be implemented as a macro, so the argument passed should not be an expression with potential side effects. See putchar for a similar function without stream parameter. Return Value If there are no errors, the same character that has been written is returned. If an error occurs, EOF is returned and the error indicator is set.

fgets char * fgets ( char * str, int num, FILE * stream ); Get string from stream Reads characters from stream and stores them as a C string into str until (num-1) characters have been read or either a newline or a the End-of-File is reached, whichever comes first. A newline character makes fgets stop reading, but it is considered a valid character and therefore it is included in the string copied to str. A null character is automatically appended in str after the characters read to signal the end of the C string. Return Value On success, the function returns the same str parameter. If the End-of-File is encountered and no characters have been read, the contents of str remain unchanged and a null pointer is returned. If an error occurs, a null pointer is returned. Use either ferror or feof to check whether an error happened or the End-of-File was reached.

fgets Example /* fgets example */ #include <stdio.h> int main() { FILE * pFile; char mystring [100]; pFile = fopen ("myfile.txt" , "r"); if (pFile == NULL) perror ("Error opening file"); else { fgets (mystring , 100 , pFile); puts (mystring); fclose (pFile); } return 0;

fputs int fputs ( const char * str, FILE * stream ); Write string to stream Writes the string pointed by str to the stream. The function begins copying from the address specified (str) until it reaches the terminating null character ('\0'). This final null-character is not copied to the stream. Return Value On success, a non-negative value is returned. On error, the function returns EOF.

fputs example /* fputs example */ #include <stdio.h> int main () { FILE * pFile; char sentence [256]; printf ("Enter sentence to append: "); fgets (sentence,255,stdin); pFile = fopen ("mylog.txt","a"); fputs (sentence,pFile); fclose (pFile); return 0; }

fprintf int fprintf ( FILE * stream, const char * format, ... ); Write formatted output to stream Writes to the specified stream a sequence of data formatted as the format argument specifies. After the format parameter, the function expects at least as many additional arguments as specified in format.

Standard Format Specifiers c Character d or i Signed decimal integer E Scientific notation (mantise/exponent) using e character E Scientific notation (mantise/exponent) using E character f Decimal floating point g Use the shorter of %e or %f 392.65 G Use the shorter of %E or %f 392.65 o signed octal s String of characters u Unsigned decimal integer x Unsigned hexadecimal integer X Unsigned hexadecimal integer (capital letters) p Pointer address

fscanf int fscanf ( FILE * stream, const char * format, ... ); Read formatted data from stream Reads data from the stream and stores them according to the parameter format into the locations pointed by the additional arguments. The additional arguments should point to already allocated objects of the type specified by their corresponding format tag within the format string. Return Value On success, the function returns the number of items succesfully read. This count can match the expected number of readings or be less -even zero- in the case of a matching failure. In the case of an input failure before any data could be successfully read, EOF is returned.

Example of fscanf /* fscanf example */ #include <stdio.h> int main () { char str [80]; float f; FILE * pFile; pFile = fopen ("myfile.txt","w+"); fprintf (pFile, "%f %s", 3.1416, "PI"); rewind (pFile); fscanf (pFile, "%f", &f); fscanf (pFile, "%s", str); fclose (pFile); printf ("I have read: %f and %s \n",f,str); return 0; }