CSC215 Lecture Input and Output.

Slides:



Advertisements
Similar presentations
File I/O.
Advertisements

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.
Binary Search Tree For a node: The left subtree contains nodes with keys less than the node's key. The right subtree contains nodes with keys greater than.
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.
CP104 Introduction to Programming File I/O Lecture 33 __ 1 File Input/Output Text file and binary files File Input/output File input / output functions.
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.
1 Lecture09: File I/O 5/6/2013 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
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.
Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee C Language Part 4.
File I/O, Project 1: List ADT Bryce Boe 2013/07/02 CS24, Summer 2013 C.
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.
Memory Layout, File I/O Bryce Boe 2013/06/27 CS24, Summer 2013 C.
Using Files Declare a variable, called file pointer, of type FILE * Use function fopen to open a named file and associate this file with the file pointer.
FILE IO in ‘C’ by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile
CS 261 – Recitation 7 Spring 2015 Oregon State University School of Electrical Engineering and Computer Science.
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.
IO revisited CSE 2451 Rong Shi. stdio.h Functions – printf – scanf(normally stops at whitespace) – fgets – sscanf Standard streams – stdin(defaults to.
Advanced Programming in the UNIX Environment Hop Lee.
6/9/2016Course material created by D. Woit 1 CPS 393 Introduction to Unix and C START OF WEEK 10 (C-4)
 Dynamic Memory Allocation  Linked Lists  void main() {{ ◦ FILE *file; ◦ char file_name[] = “file.txt”; ◦ if ((file = fopen(file_name, "w")) ==
ECE Application Programming
Chapter 4 File Processing
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
Lecture 11 File input/output
Chapter 18 I/O in C.
File I/O.
Session #5 File I/O Bit Masks, Fields & Bit Manipulations
CGS 3460, Lecture 41 Apr 21, 2006 Hen-I Yang
Plan for the Day: I/O (beyond scanf and printf)
C Programming:Part 3 Characters and Strings File Processing Exercise.
Computer Science 210 Computer Organization
CS111 Computer Programming
CSE1320 Files in C Dr. Sajib Datta
File Input/Output.
CSE1320 Files in C Dr. Sajib Datta
Computer Programming Lecture 15 Text File I/O
Programming in C Input / Output.
Computer Science 210 Computer Organization
CSE1320 Files in C Dr. Sajib Datta
File I/O We are used to reading from and writing to the terminal:
CSC215 Lecture Input and Output.
CSE1320 Strings Dr. Sajib Datta
CSC215 Lecture Input and Output.
Beginning C Lecture 11 Lecturer: Dr. Zhao Qinpei
FILE HANDLING IN C.
Programming and Data Structure
File Input and Output.
File Handling.
Line at a time I/O with fgets() and fputs()
Programming in C Input / Output.
Module 12 Input and Output
ETE 132 Lecture 8 By Munirul Haque.
File I/O & UNIX System Interface
CS1100 Computational Engineering
CSc 352 File I/O Saumya Debray Dept. of Computer Science
File I/O.
EECE.2160 ECE Application Programming
I/O CS580U - Fall 2018.
Professor Jodi Neely-Ritz University of Florida
File I/O We are used to reading from and writing to the terminal:
Files Chapter 8.
Chapter 18 I/O in C.
Presentation transcript:

CSC215 Lecture Input and Output

Outline Introduction Standard files General files I/O Command-line parameters Error handling String I/O

Introduction C has no built-in statements for input or output Input and output functions are provided by the standard library <stdio.h> All input and output is performed with streams: Stream: a sequence of bytes text stream: consists of series of characters organized into lines ending with '\n' The standard library takes care of conversion from "\r\n" to '\n' binary stream: consists of a series of raw bytes The streams provided by standard library are buffered Streams are represented by the data type FILE* FILE is a struct contains the internal state information about the connection to the file

Standard Files When a C program is started, the operating system environment is responsible for opening three files and their associated streams and providing pointers for them. These files are the : Standard input stream: called stdin normally connected to the keyboard OS knows it by number 0 Standard output stream: Called stdout normally connected to the display screen OS knows it by number 1 Standard error stream: called stderr also normally connected to the screen OS knows it by number 2

Standard Files int putchar(int char) Writes the character (an unsigned char) char to stdout returns the character printed or EOF on error int puts(const char *str) Writes the string str to stdout up to, but not including, the null character A newline character is appended to the output returns non-negative value, or EOF on error int getchar(void) reads a character (an unsigned char) from stdin returns the character read as an unsigned char cast to an int or EOF on error char *gets(char *str) Reads a line from stdin and stores it into the string pointed to by str It stops when either: the newline character is read or when the end-of-file is reached, whichever comes first. returns str on success, or NULL on error Prone to overflow problem

Standard Files What does the following code do? int scanf(const char *format, ...) Reads formatted input from stdin Prone to overflow problem when used with strings int printf(const char *format, ...) Sends formatted output to stdout void perror(const char *str) prints a descriptive error message to stderr string str is printed, followed by a colon then a space. What does the following code do? int main ( ){ char c ; while ((c=getchar())!= EOF){ if ( c >= 'A' && c <= 'Z') c = c − 'A' + 'a'; putchar(c) ; } return 0;

General Stream I/O So far, we have read from the standard input and written to the standard output C allows us to read data from any text/binary files FILE∗ fopen(char *filename,char *mode) opens file filename using the given mode returns a pointer to the file stream or NULL otherwise. int fclose(FILE∗ fp) closes the stream (releases OS resources). all buffers are flushed. returns 0 if successful, and EOF otherwise. automatically called on all open files when program terminates r For reading. File must exist w Creates empty file for writing. If file exists, it content is erased. a Appends to an existent file. Creates one if not exist. r+ For reading & writing. File must exist w+ Creates a file for reading & writing. a+ For reading and appending

General Stream I/O int getc(FILE∗ stream) reads a single character from the stream. returns the character read or EOF on error/end of file. char* fgets(char *line, int maxlen, FILE∗ fp) reads a single line (upto maxlen characters) from the input stream (including linebreak) stops when reading n-1 characters, reading \n or reaching end of file returns a pointer to the character array that stores the line returns NULL if end of stream. int fscanf(FILE∗ fp, char *format, ...) similar to scanf,sscanf reads items from input stream fp. returns the number of input items successfully matched and assigned. It stops reading after encountering the first space character.

General Stream I/O int putc(int ch, FILE∗ fp) writes a single character ch to the output stream. returns the character written or EOF on error. we can implement it as follows: #define putchar(c) putc(c,stdout) int fputs(char *line, FILE∗ stream) writes a single line to the output stream. returns 0 on success, EOF otherwise. int fprintf(FILE *stream, const char *format, ...) sends formatted output to a stream returns total number of characters written, otherwise, a negative number is returned. void rewind(FILE *stream) sets file position to beginning of stream.

Example 1: #include <stdio.h> #include <stdlib.h> int main(){ char str1[10], str2[10], str3[10]; int cNumber; FILE * fpo, *fpi; fpo = fopen ("file.txt", "w"); fputs("I love CSC 215", fpo); fclose(fpo); fpi = fopen ("file.txt", "r"); fscanf(fpi, "%s %s %s %d", str1, str2, str3, &cNumber); printf("Read String1 |%s|\n", str1 ); printf("Read String2 |%s|\n", str2 ); printf("Read String3 |%s|\n", str3 ); printf("Read Integer |%d|\n", year ); fclose(fpi); return(0);}

Example 2: #include<stdio.h> #include <stdlib.h> void filecopy(FILE *fpin, FILE *fpout); int main() { FILE *fpi, *fpo; fpi = fopen("file.c", "r"); // Open a file to read from fpo = fopen("out.c", "w"); // Open a file to write to if (fpi == NULL || fpo == NULL) printf("Error opening file\n"); // There was an error in opening either file else filecopy (fpi, fpo); // Function to copy one file to the other fclose(fpi); fclose(fpo); // Close the files when done } return 0; } void filecopy(FILE *fpin, FILE *fpout) int c; while ((c = fgetc(fpin)) != EOF) fputc(c, fpout);

Example 3: #include <stdio.h> #include <stdlib.h> main(){ FILE * fp; fp = fopen ("file.txt", "w"); fprintf(fp, "%s %s %s %d", "We", "are", "in", 2016); fclose(fp); }

Example 4: Count the number of $ sign #include <stdio.h> int main () { FILE * pFile; int c; int n = 0; pFile=fopen ("myfile.txt","r"); if (pFile == NULL) printf(“Can’t open %s\n”,"myfile.txt" ); else{ do { c = fgetc (pFile); if (c == '$') n++; } while (c != EOF); fclose (pFile); printf ("The file contains %d dollar sign characters ($).\n",n); } return 0; }

Handling Files int remove(const char *filename) deletes the given filename so that it is no longer accessible. returns 0 on success and -1on failure and errno is set appropriately int rename(const char *old_filename, const char *new_filename) causes filename referred to, by old_filename to be changed to new_filename.

Command line Input In addition to taking input from standard input and files, you can also pass input while invoking the program. so far, we have used int main() as to invoke the main function. however, main function can take arguments that are populated when the program is invoked. int main(int argc,char∗ argv[]) argc: count of arguments. argv: an array of pointers to each of the arguments note: the arguments include the name of the program as well Examples: ./cat a.txt b.txt ( argc = 3 , argv[0] = "cat" , argv[1] = "a.txt" and argv[2] = "b.txt" ) ./cat ( argc = 1 , argv[0] = "cat" )

Error Handling No direct support for error handling stderr output stream for errors assigned to a program just like stdin and stdout appears on screen even if stdout is redirected exit function terminates the program from any function, must include stdlib.h argument is passed to the system EXIT_FAILURE , EXIT_SUCCESS: defined in stdlib.h

Error Handling: Example revisited #include <stdio.h> #include <stdlib.h> int main (){ FILE * pFile; int c; int n = 0; pFile=fopen ("myfile.txt","r"); if (pFile == NULL) fprintf(stderr, “Can’t open %s\n”,"myfile.txt" ); exit(1); do { c = fgetc (pFile); if (c == '$') n++; } while (c != EOF); fclose (pFile); printf ("The file contains %d dollar sign characters ($).\n",n); return 0; }

String I/O Instead of writing to the standard output, the formatted data can be written to or read from character arrays. int sprintf(char *str, const char *format, ...) format specification is the same as printf. output is written to str (does not check size). returns number of character written or negative value on error. int sscanf(const char *str, const char *format, ...) format specification is the same as scanf; input is read from str variable. returns number of items read or negative value on error.

Example: #include <stdio.h> #include <math.h> int main() { char str[80]; sprintf(str, "Value of Pi = %f", M_PI); puts(str); return(0); } #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { int day, year; char weekday[20], month[20], dtm[100]; strcpy( dtm, "Saturday March 25 1989" ); sscanf( dtm, "%s %s %d %d", weekday, month, &day, &year ); printf("%s %d, %d = %s\n", month, day, year, weekday ); return(0); }