Plan for the Day: I/O (beyond scanf and printf)

Slides:



Advertisements
Similar presentations
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.
Advertisements

BITS Pilani, Pilani Campus TA C252 Computer Programming - II Vikas Singh File Handling.
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.
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.
CS1061 C Programming Lecture 17: Steams and Character I/O A. O’Riordan, 2004.
File I/O.
Engineering H192 - Computer Programming The Ohio State University Gateway Engineering Education Coalition Lect 6P. 1Winter Quarter I/O in C Lecture 6.
CSE1301 Computer Programming: Lecture 19 File I/O
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.
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.
© Janice Regan, CMPT 128, Jan CMPT 128: Introduction to Computing Science for Engineering Students C File Input and Output Checking input for errors.
Chapter 5: Data Input and Output Department of Computer Science Foundation Year Program Umm Alqura University, Makkah Computer Programming Skills
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.
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.
Chapter 18 I/O in C.
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.
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.
Lecture 11: Files & Arrays B Burlingame 18 November 2015.
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:
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
IO revisited CSE 2451 Rong Shi. stdio.h Functions – printf – scanf(normally stops at whitespace) – fgets – sscanf Standard streams – stdin(defaults to.
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.
Strings CSCI 112: Programming in C.
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
Chapter 18 I/O in C.
File I/O.
Introduction to C CSE 2031 Fall /3/ :33 AM.
CS 261 – Recitation 7 Fall 2013 Oregon State University
Input/Output (Continued)
CSC215 Lecture Input and Output.
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.
Programming in C Input / Output.
Files I/O, Streams, I/O Redirection, Reading with fscanf
CSE1320 Files in C Dr. Sajib Datta
I/O in C Lecture 6 Winter Quarter Engineering H192 Winter 2005
CSC215 Lecture Input and Output.
CSE1320 Strings Dr. Sajib Datta
CSC215 Lecture Input and Output.
Programming and Data Structure
File Input and Output.
File Handling.
Programming in C Input / Output.
Weeks 9-10 IO System Calls Standard IO (stdin, stdout) and Pipes
Module 12 Input and Output
Introduction to C EECS May 2019.
EECE.2160 ECE Application Programming
CS1100 Computational Engineering
CSc 352 File I/O Saumya Debray Dept. of Computer Science
EECE.2160 ECE Application Programming
Professor Jodi Neely-Ritz University of Florida
I/O CS580U - Fall 2018.
Chapter 18 I/O in C.
Presentation transcript:

Plan for the Day: I/O (beyond scanf and printf) Input and Output Topic 7 Plan for the Day: I/O (beyond scanf and printf)

Standard, String and File I/O

I/O in C Input and output facilities provided by standard library <stdio.h> and not by the language Text stream consists of series of lines ending with '\n'

Standard Input & Output int putchar(int c) prints char c to stdout Returns c, or EOF on error int getchar() Returns next character from stdin Returns EOF on error EOF = end of file character

Standard I/O #include<stdio.h> int main() { char c; printf("Enter a character: "); c = getchar(); printf("Character entered was: "); putchar(c); } CExamples/IOExamples/getPutChar.c

Standard Input & Output What does this do? int main() { char c; while((c = getchar()) != EOF) { if(c >= 'A' && c <= 'Z') c = c – 'A' + 'a'; putchar(c); } return 0; In Unix: to use a file instead of stdin, use < operator Input redirection: ./a.out < file.txt Treats file.txt as source of standard input Ctrl-Z or Ctrl-D or Ctrl-C to produce EOF (depending on OS) CExamples/IOExamples/testGetChar.c

String Input/Output Write formatted output to a string: int sprintf(char str[], char format[], arg-list) Format specification same as printf Output written to str, size not checked Returns # of characters written (excluding '\0') or negative value on error Read formatted input from a string: int sscanf(char str[], char format[], var-address-list) format specification same as scanf Input read from str Returns # of variables filled or EOF on error Remember that scanf, sscanf, fscanf leaves behind any \n on the input stream Also: scanf automatically put null at end of input string printf, puts assume output string ends with null Make scanf safer by using the conversion specifier %ns, where n specifies max number of chars to be read CExamples/IOExamples/sprintfEx.c, sprintfEx2.c

Example Example: int age; char name[20]; char str[80] = "Sarah 23"; sscanf(str, "%s %d", name, &age); printf("Name: %s, age: %d\n", name, age); Example: Use sprintf to convert a double into an array of characters: char answer[100]; double number = 93.214; sprintf(answer, "%f", number); printf("%c\n", answer[0]); Output: Name: Sarah, age: 23 Code: CExamples/IOExamples/sscanfFun.c If I print the return value of sscanf, I'll get 2 Exercise: Change this example so I make sure not to read too long a string into name Read from str Print to answer Output: 9

Files Open a text or binary file: FILE* fopen(char name[], char mode[]) modes: "r" (read only), "w" (write only), "a" (append). Append "b" for binary files Returns pointer to file if it exists, NULL otherwise (creates new file for mode "w") Close stream: int fclose(FILE* fp) fclose() automatically called on all open files when program terminates CExamples/IOExamples/fileEx.c stdin and stdout are also type FILE* stderr corresponds to standard error output (different from stdout) – different window on screen

Example #include<stdio.h> int main() { FILE* fp = fopen("example.txt", "r"); if(fp == NULL) { printf("Can't open %s\n", "example.txt"); exit(1); // failure } // Read from the file... fclose(fp); return 0;

File Path In Windows, specify path with \\ or / instead of \ Use the call fopen("c:\\project\\test1.dat", "r"); or fopen("c:/project/test1.dat", "r");

File Input reads one character from stream int getc(FILE* fp) reads one character from stream returns that character or EOF (error or end of file) Note: getchar uses stdin to read a character char *fgets(char *line, int maxlen, FILE* fp) reads single line up to maxlen-1 characters from input, including (possibly) line break '\n' returns a pointer to character array line returns NULL if end of stream fgets stops reading when it reaches \n, but includes \n in the string Returns line if no error. NULL is returned if no chars read and end of file encountered. CExamples/IOExamples/fileEx2.c. (getc example)

File Input int fscanf(FILE* fp, char format[], var-address-list) like scanf and sscanf except items read from input stream fp Cexamples/IOExample/fscanfEx.c

File Output int putc(int c, FILE* fp) writes character c to output stream returns c (or EOF on error) Note: putchar is equivalent to putc(c, stdout) int fputs(char line[], FILE* fp) writes line to output stream returns 0 on success, EOF otherwise int fprintf(FILE *fp, char format[], var-list) Similar to printf, sprintf CExamples/IOExamples/fprintfEx.c

Example /* Read line from keyboard & write to file */ int main() { char fileName[80]; char str[80]; FILE *fp; printf("Enter file name: "); scanf("%79s", fileName); // remember: \n still in input stream getchar(); // grab newline character printf("Filename: %s\n", fileName); //fgets(fileName, 80, stdin); // Alternative: remember that \n // included in string though fp = fopen(fileName, "w"); if(fp == NULL) { printf("File %s failed to open\n", fileName); exit(EXIT_FAILURE); } printf("Enter a string: "); fgets(str, 80, stdin); fputs(str, fp); fclose(fp); CExamples/IOExamples/fileEx.c fgets: reads characters from stream and stores them in string str until 79 characters have been read or newline or EOF reached Newline makes fgets stop reading but is also included in string str Note: exit() is in stdlib.h. Terminates calling procedure immediately, returning status EXIT_FAILURE is macro – indicates unsuccessful termination

Exercise Write a program that reads in all the lines from a file, and writes each line to the console, inserting the line number at the beginning of the line.