Files I/O, Streams, I/O Redirection, Reading with fscanf

Slides:



Advertisements
Similar presentations
Character Arrays (Single-Dimensional Arrays) A char data type is needed to hold a single character. To store a string we have to use a single-dimensional.
Advertisements

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.
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,
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.
Console and File I/O - Basics Rudra Dutta CSC Spring 2007, Section 001.
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.
Files COP3275 – PROGRAMMING USING C DIEGO J. RIVERA-GUTIERREZ.
C Basic File Input/Output Manipulation C Programming – File Outline v File handling in C - opening and closing. v Reading from and writing to files.
File Handling Spring 2013Programming and Data Structure1.
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.
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:
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:
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
Computer Science: A Structured Programming Approach Using C1 Objectives ❏ To understand the basic properties and characteristics of external files ❏ To.
CSC Programming for Science Lecture 18: More Data Files.
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.
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.
Error handling I/O Man pages
User-Written Functions
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.
Chapter 7 Text Input/Output Objectives
File Access (7.5) CSE 2031 Fall July 2018.
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
Plan for the Day: I/O (beyond scanf and printf)
CS111 Computer Programming
CSE1320 Files in C Dr. Sajib Datta
CSE1320 Files in C Dr. Sajib Datta
Programming in C Input / Output.
Programming in C Input / Output.
Strings, Line-by-line I/O, Functions, Call-by-Reference, Call-by-Value
Hank Childs, University of Oregon
CSE1320 Files in C Dr. Sajib Datta
I/O in C Lecture 6 Winter Quarter Engineering H192 Winter 2005
Beginning C Lecture 11 Lecturer: Dr. Zhao Qinpei
File I/O in C Lecture 7 Narrator: Lecture 7: File I/O in C.
FILE HANDLING IN C.
Programming and Data Structure
File Input and Output.
File Handling.
Accessing Files in C Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition,
Fundamental of Programming (C)
Line at a time I/O with fgets() and fputs()
Programming in C Input / Output.
Files.
Module 12 Input and Output
Introduction to C EECS May 2019.
Chapter 11 Files chap8.
C Programming - Lecture 3
CSc 352 File I/O Saumya Debray Dept. of Computer Science
Professor Jodi Neely-Ritz University of Florida
Professor Jodi Neely-Ritz University of Florida
Files Chapter 8.
Presentation transcript:

Files I/O, Streams, I/O Redirection, Reading with fscanf CS 240 – Lecture 6 Files I/O, Streams, I/O Redirection, Reading with fscanf

Files – FILE type and fopen Often times, it's important to read stored content off of the file system. stdio.h includes a suite of functions for the access and modification of files. To handle a file in C, one must declare a FILE pointer-type variable. FILE *inputfile; Then, you need to assign to that variable an opened file. Opening a file can be done in a number of modes: r (for read), w (for write), a (for append). There are more modes but they aren't important right now. inputfile = fopen("filename.ext", "r");

Files – fopen The fopen function takes two arguments, a file name and a mode. fopen(filename, mode) Modes are string values: "r" for reading; the file can be read from using fgets "w" for writing; this will delete the files contents if it already exists. "a" for appending; this will add new content to the end of a file if it already exists. If the program has permission in that folder to read/write files, the function will return a non-zero FILE* value. If the program does not have permission or there is some other error, it will return NULL, a zero value.

Files – Reading with fgets Reading files is nearly identical to the way we read input. Using fgets, instead of specifying stdin, we can simple specify the FILE* for the file that we want to read from. FILE *inputfile = fopen("input.txt", "r"); if (fgets(buffer, 1000, inputfile)) /* successfully read line from file */ Effectively, reading from a file and reading from the console are treated exactly the same by the operating system. This will give us some interesting leverage later on for combining existing programs together.

Files – Writing with fprintf We're familiar with printf for our outputting needs, but it's actually a wrapper over a more versatile function. fprintf(stream, formatstring, arguments…) fprintf functions just like printf except that it will output to any stream (either a file or screen). Not discussed before, but both functions return a negative on failure to output. The first argument is a stream, and the rest are the arguments to printf. Similar to fgets allowing us to specify a file or stdin, we can specify a file or stdout. FILE *outputfile = fopen("outputfile.txt", "w"); fprintf(stdout, "Hi!"); fprintf(outputfile, "Hey, %s", name);

Files – fflush One important thing to note about output is that your content will not be immediately sent to it's destination as you print it. This is to avoid slowdown in the operating system by programs which output one byte at a time. It's more efficient to store output temporarily in a buffer and commit output to a destination when the buffer gets full or some signal character is sent. For example, you may notice that your programs usually wait for you to hit Enter before doing anything with your input. To force the operating system to commit the output on a stream, we use fflush(stream).

Files – fclose When opening files, you need to be aware of the resources of the machine. Whenever you open a file for reading or writing, the OS has to mediate communication between your program and the filesystem. This is done through file descriptors, and there are a limited amount of them at any one time. When the system runs out of file descriptors, opening files will fail. When you are done with a file, you should run fclose(stream) to release the resource. On Windows, failing to fclose a file may result in the file being inaccessible by other programs until your program terminates.

I/O Redirection – File to Standard Input Again, since files and console output are treated identically by the machine, we should be able to use files whenever we're expected to use written input. Without having to recompile a program to change which stream it's reading from, we can use what's called Redirection. prog arg1 arg2 <input.txt Input redirection uses the less-than (<) operator next to the file. This is done in the Linux command-line when writing a command. This is incredibly useful going forward for testing your code. Simply type out the input you expect to give manually and save it to a file.

I/O Redirection – Standard Output to File It stands to reason that if you want to save the output of a program to a file, you should be able to redirect output, as well. Well, you can: prog arg1 arg2 >output.txt This will delete all the original content of output.txt if it existed. If you want to append output to the file, keeping the original content: prog arg1 arg2 >>output.txt Writing to the file uses the greater-than (>) operator Appending to the file uses the double greater-than (>>) operator.

I/O Redirection – Pipes, Program to Program Often, you'll find yourself wanting to connect the output of one program to the input of another. For example, in PuTTY, you can only scroll back 200 lines of console. If you're in a folder with over 200 files, ls -l redirected into less will allow you to view all of them without cutoff. Try it. This is called piping and uses the pipe (|) operator. prog1 arg1 arg2 | prog2 argA argB The programs will actually run concurrently, stopping only if waiting for input from the previous. You can actually continue to stack pipe connections between programs indefinitely. prog1 | prog2 | prog3 | …

Input – Reading Numeric Values w/ fscanf One thing to note when dealing with input is that content from file and console streams will be in raw text. Reading in a number with fgets will not grant you a numeric value! If you want to read the text representation of a number as a numeric value, you need to use fscanf. fscanf works like fprintf in reverse, it takes content from the stream and puts the values at the specified addresses. fscanf(stream, format, arguments); The arguments after the format string must be addresses. This is similar to passing a char[] as a buffer to fgets. Remember: for numeric variables, get their addresses with &varname.

Input – fscanf (continued) fscanf will read one character at a time from input, matching each character against the format string. Once it reaches a placeholder (%d for example), it tries to parse the next characters in input as part of that value. If it cannot, we have a match error and fscanf stops reading input. Whitespace characters are placeholders for any number of whitespace characters. Non-whitespace characters must match up exactly or there will be a match error. The return value of fscanf is int-type and indicates the number of arguments successfully read from the stream. 0 if it reads no items and fails to match the format string. EOF or -1 if it encounters a end-of-file or a read error.

Input – fscanf Examples int a; char b; fscanf(stdin, "%d %c", &a, &b); Input: "10 x" Return Value: 2 Variables: Input remaining: "" Input: "10 10" Return Value: 2 Variables: Input remaining: "0" Input: "10" Return Value: 1 Variables: Input remaining: "" int a 10 char b x int a 10 char b '1' int a 10 char b *junk*

Input – fscanf Examples int a; int b; fscanf(stdin, "(%d,%d)", &a, &b); Input: "(5,6)" Return Value: 2 Variables: Input remaining: "" Input: "(5,X6)" Return Value: 1 Variables: Input remaining: "X6)" Input: "5,6)" Return Value: 0 Variables: Input remaining: "5,6)" int a 5 int b 6 int a 5 int b *junk* int a *junk* int b *junk*

Input – fscanf Examples char a; int b; char c; int d; fscanf(stdin, "%c,%d", &a, &b); /* first */ fscanf(stdin, "%c,%d", &c, &d); /* second */ Input: "x,10\ny,20" First Return Value: 2 Variables: First Input remaining: "\ny,20" Second Return Value: 2 Variables: Second Input remaining: "" Input: "x 10\ny 20" First Return Value: 1 Variables: First Input remaining: " 10\ny 20" Second Return Value: 1 Variables: Second Input remaining: "0\ny 20" char a x int b 10 char c y int d 20 char a x int b *junk* char c 1 int d *junk*