I/O CS580U - Fall 2018.

Slides:



Advertisements
Similar presentations
Week 5 Part I Kyle Dewey. Overview Exam will be back Thursday New office hour More on functions File I/O Project #2.
Advertisements

I/O means Input and Output. One way: use standard input and standard output. To read in data, use scanf() (or a few other functions) To write out data,
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.
File I/O.
 Types of files  Command line arguments  File input and output functions  Binary files  Random access.
Chapter 18 I/O in C. Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Standard C Library I/O commands.
CMPE13 Cyrus Bazeghi Chapter 18 I/O in C. CMPE Standard C Library I/O commands are not included as part of the C language. Instead, they are part.
Standard Input and Output. Overview Data communication with a C program and the outside world is performed through files Files are a non-volatile way.
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.
Chapter 18 I/O in C.
1 Lecture09: File I/O 5/6/2013 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
Characters and Strings File Processing Exercise C Programming:Part 3.
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.
Memory Layout, File I/O Bryce Boe 2013/06/27 CS24, Summer 2013 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 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.
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:
C Programming Lecture 12 : File Processing
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.
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.
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.
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.
Chapter 7 Text Input/Output Objectives
Chapter 7 Text Input/Output Objectives
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 7 Text Input/Output Objectives
Chapter 18 I/O in C.
File I/O.
Session #5 File I/O Bit Masks, Fields & Bit Manipulations
CSC215 Lecture Input and Output.
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.
Programming in C Input / Output.
Computer Science 210 Computer Organization
Programming in C Input / Output.
Files I/O, Streams, I/O Redirection, Reading with fscanf
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.
CSC215 Lecture Input and Output.
Chapter 18 I/O in C.
Programming and Data Structure
Text and Binary File Processing
File Handling.
Fundamental of Programming (C)
Programming in C Input / Output.
C Input / Output Prabhat Kumar Padhy
Module 12 Input and Output
CS1100 Computational Engineering
File I/O.
Professor Jodi Neely-Ritz University of Florida
File I/O We are used to reading from and writing to the terminal:
Chapter 18 I/O in C.
Presentation transcript:

I/O CS580U - Fall 2018

What is input? Kinds of input? Sources of input?

This is Input Any data coming into an executing program from an outside source Sources Device (user) Keyboard, mouse File Binary or text Memory/Network another program?

Input is a String All input comes in as a string some functions do conversion for you scanf() converts based on type This means the data type of all input is what? Char <enter>, <space>, <tab> are all whitespace characters represented by an escape, “\<character>” “\n” = new line (enter or return) “\t” = tab printing escape characters Use an extra “\” to escape escape characters “\\n” prints “\n”

Important fact that will save you hours of debugging if you remember it Input is always only read one character at a time at the lowest level When you press enter, you are submitting a character for the computer to process, represented in C as ‘\n’ The following is equivalent for the computer: “Hello there” “Hello\nthere\0”

FILE * Library object that holds information about a memory location for C programs, all input and output goes through FILE * Not necessarily a file, can be File Device Volatile Memory

Streams Streams are library macros for FILE * Streams are one way Allows redirection of I/O to or from devices Treats devices as if they were files Streams are one way Data enters stream one end, exits the other Some streams are instant, some have delays (buffered Door (non buffered) vs Tunnel (buffered)

Stream usage example 3 standard streams available in C stdin (0) stdout (1) stderr (2) redirectable

Example of stdin, stdout, stderr char buff[255]; //library function scanf uses stdin stream scanf(“\n%s\n”, buff); //printf uses stdout stream printf(“\n%s\n”, buff); //fprintf uses chosen stream fprintf(stderr, “\n%s\n”, buff);

User Input Take input from a user during program execution: scanf(); from stdin to a specified format getchar(); from stdin 1 byte at a time char * gets ( char * str ); don't use gets(), no bounds checking. Continues reading until newline or end of file Terminal input always come from stdin

scanf() interface: int scanf ( const char * format, ... ) … means any number of variables matching the number of format specifiers Format specifiers, just like printf %d requires a pointer (why?) example: scanf(“%d”, &x) All scanf parameters are pointers We need the address to store the data, not the data itself

scanf - %s %s works differently in scanf() scans up to next whitespace character, adds a null byte example scanf(“%s”, buff) “hello there” buff contains “hello”

The Scan Check like gets, scanf does not automatically do bounds checking Buffer overrun ALWAYS limit how much you scan to the size of your buffer char str[50]; scanf(“%50s”, &str);

Takeaways so far All I/O is via a FILE * I/O can be wrapped in streams to get I/O to or from devices Use scanf() for structured user input Always limit strings in scanf() to the buffer size or less

Buffering

Buffered Output Buffered : stored in a memory ‘bucket’ for later use Usually to increase performance Most output is buffered stdin, stdout streams are buffered stderr is not

Buffering complications double n, m; double pi = 3.14159; char buffer[256]; printf("Enter degrees: "); fgets(buffer, 256, stdin); n = atof(buffer); m = sin(n * pi / 180); Which executes first? Which ‘outputs’ first?

Buffering complications double n, m; double pi = 3.1415926535; char buffer[256]; printf("Enter degrees: "); fflush(stdout); fgets(buffer, 256, stdin); n = atof(buffer); m = sin(n * pi / 180); Flushes output stream

Debugging When debugging, it is often better to use fprintf() int fprintf ( FILE * stream, const char * format, ... ); Allows you to define a stream stderr is non-buffered bad for performance, good for debugging Always use fprintf(stderr, “my debug statement”) for debugging this ensures output isn’t buffered

Always flush Flushing the output Flushing the input use fflush(FILE *) example: fflush(stdin) Flushing the input There is no easy way to flush input You must know your input format Input Flushing technique while ( getchar() != '\n' ); //why does this work?

Buffered Input All input must be buffered You are too slow for the computer, so it has to buffer Input is read into memory, and sent to the executing program as it requests it Every character you press on the keyboard is sent to the input buffer Including the enter key

Fix Me void foo(int x){ printf(“DEBUG : %d”, x); char buff[255]; if(x < 100){ scanf(“%d %s”, x, buff ); } … }

//Corrected void foo(int x){ fprintf(stderr, “DEBUG : %d”, x); char buff[255]; if(x < 100){ scanf(“%d %255s”, &x, buff ); } … }

Classwork: Streams int main(){ fprintf(stdout, “first”); fprintf(stderr, “second”); char let = ' '; while(let != 'n' and let != 'N'){ fprintf(stdout, "Would you like to continue?"); let = getchar(); while(getchar() != '\n'); } Classwork: Streams

Command Line Arguments

Command Line Arguments Strings sent in as parameters to main Optional parameters to main, argc and argv int main(int argc, char * argv[]) argc : argument count, i.e. number of parameters including program name argv: array of strings containing the parameters $> ./prog hello there The above command runs the executable file prog, passing the command line arguments “hello” and “there” Passed arguments are separated by spaces in the command There is no limit to the number of arguments you can send

Using CLA Remember: All arguments come in as strings argc: allows you to loop through arguments and index into the argv array Use argc for error checking if(argc < 3){ printf(“usage: ./prog arg1 arg2\n”); } else{ printf(“\n %s %s \n”, argv[1], argv[2]); } The name of the executable is always the first argument argv: a two dimensional character array

What size argv array does this produce? $ >./foo hello world config.txt 123 vars.exe 6

File IO

File I/O File input works the same as stdin/stdout, except for the file position indicator The File Position Indicator (sometimes also called file pointer) is a bookmark for where you are in the file when reading or writing EOF - library macro indicating end of file

File Open fopen opens a file stream and returns a FILE * to it FILE * fopen ( const char * filename, const char * mode ); Because streams are one way, you must define the kind of stream or mode r read from file, starting from beginning w write to file, truncate if it already exists a write to file, append if it already exists *+ read and write, according to *

fopen() Usage FILE * fptr = fopen(“myfile.txt”, “r”); opens myfile.txt in the same directory as the executable for reading fopen(“config/myconfig.txt”, “w”); opens myconfig.txt in the config directory for writing, clearing its contents fopen(“binary.exe”, “a+”); opens the binary.exe file for read/write to preserving its contents

File Close fclose(FILE *) ALWAYS close files when done Remember that output is buffered if the program exits before the buffer completes writing, data is lost usage: fclose(fp) guarantees all buffered output will be written

File Write fprintf(FILE*, const char * format , …) write to a file using format specifiers at the current position usage fprintf(fp, “%s”, buff);

File Read Read from a file, and store in a variable For structure format: fscanf(FILE *, const char *, …) Does automatic type conversion For unstructured format: fgets(char *, int , FILE *) fgets reads a specified number of bytes, and saves it int a char buffer

File Position Indicator Set the position with fseek() works with bytes, not lines Usage: fseek(FILE *, int offset, int origin) origin = SEEK_SET | SEEK_CUR | SEEK_END SEEK_SET : Beginning of file SEEK_CUR : current position SEEK_END : end of file

Classwork: Passkey int main(){ fprintf(stdout, “first”); fprintf(stderr, “second”); fprintf(stdout, “first\n”); fprintf(stderr, “second\n”); char c = ‘ ‘; while(c != ‘n’){ c = getchar(); while(getchar() != ‘\n’); } printf(“Please enter a number and a username: ”); fflush(stdout); char buff[255] = {0}; int num = 0; scanf(“%d %255s”, &num, buff); FILE * fptr = fopen(“username.key”, w); for(char * ptr = buff; ptr != NULL; ptr++) fprintf(fptr, “%c”, (((*ptr)+num) % 62) + 65); fclose(fptr); } Classwork: Passkey