Standard C Library Functions

Similar documents
Input / Output Functions

CSci 4061 Introduction to Operating Systems. Input/Output: High-level

System Software Experiment 1 Lecture 7

Standard File Pointers

UNIT IV-2. The I/O library functions can be classified into two broad categories:

C mini reference. 5 Binary numbers 12

CS240: Programming in C

Input/Output and the Operating Systems

C programming basics T3-1 -

File IO and command line input CSE 2451

Quick review of previous lecture Ch6 Structure Ch7 I/O. EECS2031 Software Tools. C - Structures, Unions, Enums & Typedef (K&R Ch.

C Basics And Concepts Input And Output

Accessing Files in C. Professor Hugh C. Lauer CS-2303, System Programming Concepts

File (1A) Young Won Lim 11/25/16

Mode Meaning r Opens the file for reading. If the file doesn't exist, fopen() returns NULL.

C PROGRAMMING. Characters and Strings File Processing Exercise

fopen() fclose() fgetc() fputc() fread() fwrite()

Computer Programming: Skills & Concepts (CP) Files in C

ENG120. Misc. Topics

Content. Input Output Devices File access Function of File I/O Redirection Command-line arguments

Systems Programming. 08. Standard I/O Library. Alexander Holupirek

Chapter 12. Files (reference: Deitel s chap 11) chap8

File I/O. Arash Rafiey. November 7, 2017

CS 261 Fall Mike Lam, Professor. Structs and I/O

Files and Streams Opening and Closing a File Reading/Writing Text Reading/Writing Raw Data Random Access Files. C File Processing CS 2060

PROGRAMMAZIONE I A.A. 2017/2018

CSI 402 Lecture 2 Working with Files (Text and Binary)

Input/Output: Advanced Concepts

Ch 11. C File Processing (review)

CS246 Spring14 Programming Paradigm Files, Pipes and Redirection

Continued from previous lecture

Lecture 7: Files. opening/closing files reading/writing strings reading/writing numbers (conversion to ASCII) command line arguments

CS113: Lecture 7. Topics: The C Preprocessor. I/O, Streams, Files

Introduction to file management

C-Refresher: Session 10 Disk IO

Computer Programming: Skills & Concepts (CP1) Files in C. 18th November, 2010

UNIX System Programming

The Design of C: A Rational Reconstruction (cont.)

211: Computer Architecture Summer 2016

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

Goals of C "" The Goals of C (cont.) "" Goals of this Lecture"" The Design of C: A Rational Reconstruction"

Topic 8: I/O. Reading: Chapter 7 in Kernighan & Ritchie more details in Appendix B (optional) even more details in GNU C Library manual (optional)

C File Processing: One-Page Summary

Day14 A. Young W. Lim Tue. Young W. Lim Day14 A Tue 1 / 15

Lecture 8. Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson)

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 12

DATA STRUCTURES USING C

HIGH LEVEL FILE PROCESSING

The Design of C: A Rational Reconstruction (cont.)" Jennifer Rexford!

Memory Layout, File I/O. Bryce Boe 2013/06/27 CS24, Summer 2013 C

Advanced C Programming Topics

Darshan Institute of Engineering & Technology for Diploma Studies Unit 6

Copyright The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

File I/O. Preprocessor Macros

The Design of C: A Rational Reconstruction: Part 2

Lecture 9: File Processing. Quazi Rahman

Course organization. Course introduction ( Week 1)

File Processing. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan

Chapter 11 File Processing

System Programming. Standard Input/Output Library (Cont d)

Organization of a file

Basic I/O. COSC Software Tools. Streams. Standard I/O. Standard I/O. Formatted Output

Intermediate Programming, Spring 2017*

Day14 A. Young W. Lim Thr. Young W. Lim Day14 A Thr 1 / 14

CSE 230 Intermediate Programming in C and C++ Input/Output and Operating System

Standard I/O in C, Computer System and programming in C

8. Characters, Strings and Files

C Syntax Arrays and Loops Math Strings Structures Pointers File I/O. Final Review CS Prof. Jonathan Ventura. Prof. Jonathan Ventura Final Review

Data File and File Handling

Unit 6 Files. putchar(ch); ch = getc (fp); //Reads single character from file and advances position to next character

CSE 12 Spring 2018 Week One, Lecture Two

Lecture 8: Structs & File I/O

Files. Programs and data are stored on disk in structures called files Examples. a.out binary file lab1.c - text file term-paper.

25.2 Opening and Closing a File

Lecture6 File Processing

Computer Programming Unit v

CSE 12 Spring 2016 Week One, Lecture Two

C Programming. Unit 9. Manipulating Strings File Processing.

EE458 - Embedded Systems Lecture 4 Embedded Devel.

File I/O, Project 1: List ADT. Bryce Boe 2013/07/02 CS24, Summer 2013 C

CSCI 171 Chapter Outlines

CSI 402 Systems Programming LECTURE 4 FILES AND FILE OPERATIONS

Library Functions. General Questions

Binghamton University. CS-220 Spring Includes & Streams

IO = Input & Output 2

C Input/Output. Before we discuss I/O in C, let's review how C++ I/O works. int i; double x;

C Programming Language

CMPT 102 Introduction to Scientific Computer Programming. Input and Output. Your first program

C for Engineers and Scientists: An Interpretive Approach. Chapter 14: File Processing

Programming in C. Session 8. Seema Sirpal Delhi University Computer Centre

COMP1917: 15 File IO

CS 220: Introduction to Parallel Computing. Input/Output II. Lecture 8

Computer Security. Robust and secure programming in C. Marius Minea. 12 October 2017

Computer programming

Princeton University Computer Science 217: Introduction to Programming Systems The Design of C

mywbut.com 12 File Input/Output

UNIT-V CONSOLE I/O. This section examines in detail the console I/O functions.

File I/O. Last updated 10/30/18

Contents. A Review of C language. Visual C Visual C++ 6.0

Lecture 7: file I/O, more Unix

Transcription:

Demo lecture slides Although I will not usually give slides for demo lectures, the first two demo lectures involve practice with things which you should really know from G51PRG Since I covered much of this in the G52CFJ (C and C++) module in previous years, I have included the slides from that module here, to remind people who may not attend the demo lectures, or forget what was said

Standard C Library Functions Part of the Standard C++ Library String functions : strcpy, strncpy, strcat, strcmp, File access functions : fopen, fclose, fread, fwrite, Dynamic memory allocation : malloc/realloc/free memory Mathematical functions : sin, cos, asin, sqrt, Misc functions : e.g. random numbers You should know and use the standard library functions Documented in most C and C++ books Easy to find on the web, e.g.: http://en.wikipedia.org/wiki/list_of_c_functions http://www.cplusplus.com/reference/clibrary/ There is no excuse for not finding out

strcpy A function which uses pointers

The strcpy() function char* strcpy( char* destination, char* source) Copy the characters from one string into another Including the terminating zero ASSUMES that the destination is big enough (problem if it isn t!)

Valid destinations for strcpy? You can create char*s in many ways: 1) Just create a char*: char* str1; 2) Pointing to string literals: char* str2 = Hello ; 3) From arrays: char str3[6]; char str4[] = { H, e, l, l, o, \0 }; Question: Which of these (str1, str2, str3, str4) are good destinations to copy a string to? E.g. strcpy( str1, Test );

Answer 1) Just create a char*: char* str1; Where does str1 point? So where would the string go? 2) From string literals: char* str2 = Hello ; You should not write over a literal, see later str2 is your variable, but the thing it points to is not 3) From arrays: char str3[6]; char str4[] = { H, e, l, l, o, \0 }; This allocates enough memory to hold the array These are the best options, as long as the array is big enough! 4) Allocate dynamic memory (see lecture 7, later) Used if we don t know the required size until runtime Don t get confused between these Only 3 and 4 are (good) valid destinations for a strcpy

Input/output

Console/command line input Text input is buffered to allow editing Only sent to program when you press ENTER Program can then process input stream, using input functions EOF means End Of File (end of input) Get the next character (or EOF): int getchar() Get a string (up to newline character): gets( char* destination ) Destination MUST be big enough! How?

The scanf() function : overview Provides the inverse (?) operation for printf Reads formatted input, instead of formatting output Parameters have the same format but: It needs to be able to set the values of the parameter variables So you MUST pass pointers to the variables Examples: printf( %d %d %s, int1, int2, string1 ); scanf( %d %d %s, &int1, &int2, string1 ); Note: char* strings are already pointers You don t pass the address of a char* From the char* the string itself can be changed

The control string scanf( Name: %s %d, string1, &int1); Consists of three types of values: Whitespace: Match any whitespace Fields, labelled with % : The letter which follows specifies the type, e.g.: %s read a string up to whitespace character %d read a number %c read a character (or multiple chars) Other character: must be matched exactly, if matching fails then the read operation fails Returns number of fields matched

The letters for scanf() %d or %i Decimal integer %c Character %s String, to whitespace (space/return/ ) %u Unsigned decimal integer %x Unsigned hexadecimal number %f Floating point number %e Scientific notation You should experiment with these They are VERY similar to the printf() ones There is more to scanf() and printf() See the docs (and fscanf(), sscanf() )

File access functions

File access The operating system provides methods for: Opening a file: read or read&write? binary/text? Reading from a file (binary or text?) Writing to a file (binary or text?) Moving around within a file (if appropriate) Closing an open file Different operating systems may allow file access in different ways The C library functions wrap up the operating system calls

The C libraries : File access Hides the implementation details Provides a platform independent way to refer to files In a FILE structure fopen() : Gives you a pointer to a FILE structure that it creates when file is opened You do NOT need to know the format of FILE Do NOT assume the format it can vary Just pass back the pointer it gives you Adds buffering, so multiple writes happen at once (usually much faster)

FILE* Functions Open a file: (returns a FILE* pointer to use) FILE* pfile = fopen( Filepath, <type>) Close an open file: int fclose( FILE* pfile ) Flush the write buffer of a file: fflush( FILE* pfile ); Remember that files are buffered Read text: fgetc(), fgets(), fscanf() Write text: fputc(), fputs(), fprintf() Read binary: fread() Write binary: fwrite()

fopen() Open a file for me and give me a way to refer to it : FILE* pfile = fopen( Filepath, <type>) Example types r read, w write, a append FILE* pread = fopen( input.txt, r ); FILE* pwrite = fopen( output.txt, w ); FILE* pappend = fopen( append.txt, a ); Other types: r+ read/write (must exist) w+ create empty file for read/write a+ append to and read from existing file Add b to type for binary (avoids some conversions) See documentation for details, for example: http://www.cplusplus.com/reference/clibrary/cstdio/fopen.html

Example : fopen() FILE* pfileinput = fopen( pinputfilename, itype == 0? "rb" : "r" ); FILE* pfileoutput = fopen( poutputfilename, itype == 0? "wb" : "w" ); if ( pfileinput == NULL ) { printf( "Unable to open input file : %s\n", } pinputfilename ); return 2; if ( pfileoutput == NULL ) { printf( "Unable to open output file : %s\n", poutputfilename ); fclose(pfileinput); return 3; } Types for sample: 0 = binary 1 = scanf/printf 2 = fgetc/fputc 3 = fgets, fputs

Example : fclose() Close the files at the end fclose( pfileoutput ); fclose( pfileinput );

Example : fread(), fwrite() Usually for reading binary data char buffer[1024]; while (!feof(pfileinput) ) { } int inumberread = fread( buffer, 1, 1024, pfileinput ); fwrite( buffer, inumberread, 1, pfileoutput ); Parameters: Destination/source Size of an element Number of elements FILE*

Example : fgetc(), fputc() int ichar; For control, read a character at a time while (!feof(pfileinput) ) { ichar = fgetc(pfileinput); if ( ichar!= EOF ) fputc(ichar, pfileoutput ); }

Example : fgets(), fputs() Or read an entire line (up to and including \n) char buffer[1024]; while (!feof(pfileinput) ) { if ( fgets( buffer, 1024, pfileinput )!= NULL ) fputs( buffer, pfileoutput ); } Including final \0

Example : fscanf(), fprintf() Read a string, up to whitespace (not only \n!) char buffer[1024]; Note: it also adds a zero at the end! Buffer size 1024 Reads 1023 chars while (!feof(pfileinput) ) { if ( fscanf( pfileinput, "%1023s", buffer ) > 0 ) fprintf( pfileoutput, "%s\n", buffer ); } Useful for reading multiple fields which are separated by whitespace (tab/space?) or for reading numbers

Moving around in a file int fseek ( FILE* stream, long offset, int origin ) Move read/write position in file origin is a constant meaning one of: current position, start of file or end of file long ftell ( FILE* stream ) Ask where current read/write position is void rewind ( FILE* rewind ) Go to beginning of file

stdin, stdout and stderr Normal input and output can be accessed using the file functions stdin is standard input stream stdout is standard output stream stderr is the error output stream Use these as a FILE* in file functions Just read/write, do not open/close them Defined in stdio.h

sscanf and sprintf More printf and scanf family members: sscanf() takes a string as first parameter int sscanf(char* str, char* format,...); Read from string instead of stream (stdin or a file) sscanf( Adam 34, %s %d, pname, &iage ); sprintf() takes a string as first parameter int sprintf(char* str, char* format,... ) Write to string instead of stream (stdout or a file) Ensure that it is big enough! sprintf( string, %s %d, pname, iage ); sprintf() is useful for formatting text in a string