CS1100 Computational Engineering

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

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.
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.
Engineering H192 - Computer Programming The Ohio State University Gateway Engineering Education Coalition Lect 6P. 1Winter Quarter I/O in C Lecture 6.
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.
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.
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.
File IO and command line input CSE 2451 Rong Shi.
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:
Memory Layout, File I/O Bryce Boe 2013/06/27 CS24, Summer 2013 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:
CSE1301 Computer Programming: Lecture 6 Input/Output.
CS 261 – Recitation 7 Spring 2015 Oregon State University School of Electrical Engineering and Computer Science.
© Janice Regan, CMPT 102, Sept CMPT 102 Introduction to Scientific Computer Programming Input and Output.
GAME203 – C Files stdio.h C standard Input/Output “getchar()”
CS113 Introduction to C Instructor: Ioannis A. Vetsikas Lecture 11 : September 18.
Files A collection of related data treated as a unit. Two types Text
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.
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.
Lecture 8 String 1. Concept of strings String and pointers
Chapter 7 Text Input/Output Objectives
File Access (7.5) CSE 2031 Fall July 2018.
Chapter 18 I/O in C.
File I/O.
CS 261 – Recitation 7 Fall 2013 Oregon State University
Input / Output functions in C
CSC215 Lecture Input and Output.
Plan for the Day: I/O (beyond scanf and printf)
Arrays in C.
CS111 Computer Programming
CSE1320 Files in C Dr. Sajib Datta
File Input/Output.
CSE1320 Files in C Dr. Sajib Datta
Programming in C Input / Output.
Computer Science 210 Computer Organization
Input / Output functions in C
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:
I/O in C Lecture 6 Winter Quarter Engineering H192 Winter 2005
CSC215 Lecture Input and Output.
CSC215 Lecture Input and Output.
File I/O in C Lecture 7 Narrator: Lecture 7: File I/O in C.
Programming and Data Structure
File Input and Output.
File Handling.
File Access (7.5) CSE 2031 Fall January 2019.
File Access (7.5) CSE 2031 Fall February 2019.
Programming in C Input / Output.
File Handling in C.
Module 12 Input and Output
ETE 132 Lecture 8 By Munirul Haque.
File I/O & UNIX System Interface
Professor Jodi Neely-Ritz University of Florida
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:
Chapter 18 I/O in C.
Presentation transcript:

CS1100 Computational Engineering File I/O N.S.Narayanaswamy

Homework Problems on Arrays and Strings Given a square array of integers – produce an array rotated clockwise by 90o. Convert a string of characters in the range ‘0’ to ‘9’ to the corresponding integer look for minus sign preceding the number e.g. “ -986542is ”  the number -986542 Given an integer, produce the string of characters denoting that number e.g 926  ‘9’, ‘2’, ‘6’ Given an array of characters, extract a double number e.g “ -63.65” or “ 76.56”

C has no built-in statements for input or output Input/Output in C C has no built-in statements for input or output A library of functions is supplied to perform these operations. The I/O library functions are listed in the “header” file <stdio.h> You do not need to memorize them, just be familiar with them Programs using the library - portable Instructor: Remind students of the #include function used at the beginning of a program: #include <stdio.h> Narrator: C itself has no idea how to handle input or output from the computer. The library function stdio.h includes the information necessary for C to understand how handle input and output on the computer it is programmed for. Concerning these libraries, you don’t need to memorize what functions are where, but be familiar with them. The names of most C libraries we will use are fairly obvious and easy to remember.

All input and output is performed with streams A “stream” is a sequence of characters organized into lines Each line consists of zero or more characters and ends with the “newline” (‘\n’) character ANSI C standard specifies that the system must support lines that are at least 254 characters in length (including the newline character) Instructor: Streams include input from the keyboard and files, and output to the screen and files for programs in this class. Narrator: C handles all input and output in what are called streams. A “stream” is a sequence of characters organized into lines. Each line can contain 0 or more characters and ends with what is known as a “newline” character. This will be explained more later. The ANSI C standard specifies that the system must support lines that are at least 254 characters in length including this newline character.

Every C program has 3 standard streams: Types of Streams in C Every C program has 3 standard streams: Standard input stream is called stdin and is normally connected to the keyboard Standard output stream is called stdout and is normally connected to the display screen Standard error stream is called stderr and is also normally connected to the screen Instructor: Streams can be “connected” to other interfaces, but for the purpose of this class the standard I/O connections are acceptable. Narrator: The types of streams we are concerned with include the standard input stream called “stdin”, which is normally connected to the keyboard. Another stream called “stdout”, the standard output stream, is connected normally to the display screen or terminal being used. Another stream is the standard error stream, or “stderr.” This is also normally connected to the screen or terminal. Note that we say “normally connected” since all of these streams can be connected to other interfaces, but for the purpose of this class the default standard I/O connections are acceptable.

Input functions normally read from stdin Standard Streams in C Input functions normally read from stdin scanf( ), gets( ), getchar( ) Output functions normally write to stdout printf( ), putchar( ) I/O redirection: connect stdin or stdout to a file instead of keyboard or display Type command: myprog scanf reads from keyboard, printf writes to display Type command with file names: myprog < input.dat > output.dat scanf reads from input.dat, printf writes to output.dat Instructor: Streams can be “connected” to other interfaces, but for the purpose of this class the standard I/O connections are acceptable. Narrator: The types of streams we are concerned with include the standard input stream called “stdin”, which is normally connected to the keyboard. Another stream called “stdout”, the standard output stream, is connected normally to the display screen or terminal being used. Another stream is the standard error stream, or “stderr.” This is also normally connected to the screen or terminal. Note that we say “normally connected” since all of these streams can be connected to other interfaces, but for the purpose of this class the default standard I/O connections are acceptable.

Files need to be connected to the program File Access Files need to be connected to the program the system connects stdin, stdout, and stderr Reading from or writing to a file in C requires 3 basic steps: open the file do all the reading or writing close the file Internally a file is referred to using a file pointer points to a structure that contains info about the file

Declare a file pointer and open a file using the function fopen( ) Opening a File Declare a file pointer and open a file using the function fopen( ) FILE *fp; /* FILE is a type name, like int */ Prototype: fopen(char *name, char *mode) fp = fopen(name, mode); name of file what is the file going to be used for?

Basic Modes for Opening Files ‘r’ – Open an existing file for reading only. ‘w’ – Open the file for writing only. If the file already exists, it is truncated to zero length. Otherwise a new file is created. ‘a’ – Open a file for append access; that is, writing at the end of file only. If the file already exists, its initial contents are unchanged and output to the stream is appended to the end of the file. Otherwise, a new, empty file is created.

More File Modes ‘r+’ – Open an existing file for both reading and writing. The initial contents of the file are unchanged and the initial file position is at the beginning of the file. ‘w+’ – Open a file for both reading and writing. If the file already exists, it is truncated to zero length. Otherwise, a new file is created. ‘a+’ – Open or create file for both reading and appending. If the file exists, its initial contents are unchanged. Otherwise, a new file is created. The initial file position for reading is at the beginning of the file, but output is always appended to the end of the file.

An Example FILE *ifp, *ofp; char *mode = "r"; char inFilename[ ] = “in.list”; char outFilename[ ] = "out.list"; ifp = fopen(inFilename, mode); if (ifp == NULL) { fprintf(stderr, "Can't open input file %s!\n”, inFilename); exit(1); } ofp = fopen(outFilename, "w"); if (ofp == NULL) { fprintf(stderr, "Can't open output file %s!\n", outFilename); fopen returns NULL if it cannot open a file

File Input/Output in C getc(*file); This function is similar to getchar( ) except that the input can be from the keyboard or a file. Example: char ch; ch = getc(stdin); /* input from keyboard */ ch = getc(fileptr); /* input from a file */ Instructor: Unlike getchar(), getc isn’t connected to a certain stream automatically. It is up to the user to determine which stream to connect getc to. Narrator: A somewhat more general function which operates much like getchar() is getc(). In this case getc() isn’t automatically connected to the keyboard input stream, so it is up to the programmer to specify which stream to get a character from. This is useful when the programmer wishes to get a character from a file instead of the user. The stream is specified as the argument. In the given example the program gets one character from the keyboard via the stdin standard input stream, and then gets a character from what is known as a file pointer, which will be discussed in detail in a later lecture.

… File Input/Output in C putc(char, *file); This function is similar to putchar( ) except that the output can be to the screen or a file. Example: char ch; ch = getc(stdin); /* input from keyboard */ putc(ch, stdout); /* output to the screen */ putc(ch, outfileptr); /*output to a file */ Narrator: Of course there must also exist a putc() function to output a single character to a stream of the programmer’s choice. The putc() function requires as arguments, first the character to be placed in the stream, and then the stream to place the character into. As shown in the sample, putc can be used to write to the stdout standard output stream or to a file pointer.

Formatted Reading and Writing fscanf(filepointer, “…”, args); fprintf(filepointer, “…”, args); Format string and arguments same as with scanf( ) and printf( )

Closing a File When done with a file, it must be closed using the function fclose( ) fclose(ifp); fclose(ofp); Closing a file is very important, especially with output files. The reason is that output is often buffered. This means that when you tell C to write something out, it doesn't necessary get written to disk right away, but may be stored in a buffer in memory This output buffer holds the text temporarily When the buffer fills up (or when the file is closed), the data is finally written to disk

Force Write of File Buffer to Disk Sometimes it is necessary to forcefully flush a buffer to its stream: fflush(outf);

One of the alternatives to scanf/fscanf is fgets The prototype is: The Function fgets One of the alternatives to scanf/fscanf is fgets The prototype is: char *fgets(char *s, int size, FILE *stream); fgets reads in (size – 1) characters from the stream and stores it into *s pointer The string is automatically null-terminated Returns s or NULL if there is an error fgets stops reading in characters if it reaches an EOF or NULL The string can be scanned using sscanf( )

Reading from a File using fgets fgets is a better way to read from a file We can read into a string using fgets FILE *fptr; char line [1000]; /* Open file and check it is open */ while (fgets(line,1000, fptr) != NULL) { printf ("Read line %s\n", line); } Recall that fgets takes 3 arguments, a string, the maximum number of characters to read, and a file pointer. It returns NULL if there is an error (such as EOF).

Using fgets to Read from the Keyboard fgets and stdin can be combined to get a safe way to get a line of input from the user #include <stdio.h> int main( ) { const int MAXLEN=1000; char readline[MAXLEN]; fgets(readline, MAXLEN, stdin); printf("You typed %s", readline); return 0; }

Command Line Arguments Parameters can be passed to C programs by giving arguments when the program is executed Example: $ echo hello, world prints the output hello, world $ cat file1 file2 prints contents of file1 followed by file2 cat is short for concatenate

main(int argc, char *argv[ ]) The main program in C is called with two implicit arguments argc and argv argc is an integer value for the number of arguments in the command line if none, the program name is the only argument, so argc =1 *argv[ ] is a pointer to pointers argv[0] is the name of the program argv[1] is the first argument, and so on … argv[argc] is a null pointer

argc = 3, argv is a pointer to pointers $echo hello, world argc = 3, argv is a pointer to pointers echo\0 hello,\0 world\0 argv: a two dimensional array of characters

Implementing echo #include <stdio.h> /* echo command line arguments: 1st version */ main(int argc, char *argv[ ]){ int i; for (i = 1; i < argc; i++) printf(“%s%s”, argv[i], (i<argc – 1)? “ ” : “”); printf(“\n”); return 0; }

printf((argc > 1) ? “%s ” : “%s”, *++argv); echo – Pointer Version #include <stdio.h> /* echo comand line arguments: 2nd version */ main(int argc, char *argv[ ]){ while (--argc > 0) printf(“%s%s”, *++argv, (argc > 1)? “ ” : “”); printf(“\n”); return 0; } printf((argc > 1) ? “%s ” : “%s”, *++argv);

cat – Reads Files and Prints Them #include <stdio.h> main(int argc, char *argv[ ]){ FILE *fp; void filecopy(FILE *, FILE *) if (argc == 1) /* no args; copy from stdin */ filecopy(stdin, stdout); else /*open the first file, copy it onto screen, close it, go to next file …. */

if ((fp = fopen(*++argv, “r”) == NULL){ cat - Continued while (--argc > 0) if ((fp = fopen(*++argv, “r”) == NULL){ printf(“cat: can’t open %s\n”, *argv); return 1; } else { filecopy(fp, stdout); fclose(fp); } return 0; } /* end of main */ modify program to direct error messages to stderr, so that redirection does not affect it. cat f1 f2 > outfile

/* filecopy: copy file ifp to file ofp */ Copying a File /* filecopy: copy file ifp to file ofp */ void filecopy(FILE *ifp, FILE *ofp) { int c; while ((c = getc(ifp)) != EOF) putc(c, ofp); } copy everything, blanks, tabs, endofline, till the file ends

Program Name in Error Message . char *prog = argv[0]; if ((fp = fopen(*++argv, “r”)) == NULL){ fprintf (stderr, “%s: can’t open %s\n”, prog, *argv);

Homework Problem Set 2 Given two files file1 and file2 of integers, compute the average of all the numbers, and append file2 at the end of file1. Find the middle element of a string without calculating the length of the string. (Use pointers) Reverse the word order of a sentence using pointers Example : Chennai is capital of Tamil Nadu  Nadu Tamil of capital is Chennai Given two strings s1 and s2, write a program to say whether s2 is a rotation of s1?               Example : Tamilnadu     aduTamiln    True                                Tamilnadu     dunaTamil    False

A Problem of Managing Indices Fill in a rectangular array with increasing numbers in a spiral form, as shown for the square array 1 2 3 4 5 16 17 18 19 6 15 24 25 20 7 14 23 22 21 8 13 12 11 10 9