1 Lecture09: Global Variables, File I/O, and Variable-Length Arguments 5/16/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

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.
1 Lecture13: Other C Topics 12/17/2012. Topics Variable-length argument lists Pointers to functions Command-line arguments Suffixes for integer and floating-point.
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.
Local and Global Variables. COMP104 Local and Global / Slide 2 Scope The scope of a declaration is the block of code where the identifier is valid for.
This presentation includes custom animations. To view the animations, you must view the presentation in Slide Show mode and activeX controls must be allowed.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 11 – File Processing Outline 11.1Introduction 11.2The Data Hierarchy 11.3Files and Streams 11.4Creating.
Chapter 11 C File Processing Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
 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.
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.
Lone Leth Thomsen Input / Output and Files. April 2006Basis-C-8/LL2 sprintf() and sscanf() The functions sprintf() and sscanf() are string versions of.
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.
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.
 2007 Pearson Education, Inc. All rights reserved C File Processing.
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.
Chapter 8 : Binary Data Files1 Binary Data Files CHAPTER 8.
Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee C Language Part 4.
1 Homework HW6 On line – due next class Starting K&R Chapter 7 and Appendix B Also, UNIX – Various chapters in Glass.
ECE 103 Engineering Programming Chapter 44 File I/O Herbert G. Mayer, PSU CS Status 6/4/2014 Initial content copied verbatim from ECE 103 material developed.
1 Lecture09: File I/O 11/19/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
Lecture Starting K&R Chapter 7 and Appendix B Also, UNIX – Various chapters in Glass.
Variable Argument Lists CS 112 (slides from Marc Lihan)
Chapter 11: Data Files and File Processing Files and streams Creating a sequential access file Reading data from a sequential access file Using fgetc()
Basic I/O in C Computer Organization I 1 August 2009 © McQuain, Feng & Ribbens Stream Model of I/O header file: A stream provides a connection.
Chapter 11 File Processing. Objectives In this chapter, you will learn: –To be able to create, read, write and update files. –To become familiar with.
Chapter 12 Files (reference: Deitel ’ s chap 11) chap8.
C Program Design C File Processing 主講人:虞台文. Content Introduction Data Hierarchy Files and Streams Creating a Sequential-Access File Reading Data from.
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.
FILE IO in ‘C’ by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile
C Programming Lecture 12 : File Processing
© Janice Regan, CMPT 102, Sept CMPT 102 Introduction to Scientific Computer Programming Input and Output.
Chapter 12 Files (reference: Deitel ’ s chap 11) chap8.
1 CSC103: Introduction to Computer and Programming Lecture No 28.
CS 1704 Introduction to Data Structures and Software Engineering.
Files A collection of related data treated as a unit. Two types Text
 2007 Pearson Education, Inc. All rights reserved. 1 C File Processing.
FILES IN C. File Operations  Creation of a new file  Opening an existing file  Reading from a file  Writing to a file  Moving to a specific location.
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.
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.
 2007 Pearson Education, Inc. All rights reserved C File Processing.
C Characters and Strings
Chapter 4 File Processing
Lecture 11 File input/output
TMF1414 Introduction to Programming
Chapter 18 I/O in C.
Introduction to Computer Programming Lecture 18 Binary Files
Plan for the Day: I/O (beyond scanf and printf)
CS111 Computer Programming
File Input/Output.
Programming in C Input / Output.
Lecture 13 Input/Output Files.
C Programming Lecture-15 File I/O
Miscellaneous functions
Local Variables, Global Variables and Variable Scope
Fundamental of Programming (C)
Weeks 9-10 IO System Calls Standard IO (stdin, stdout) and Pipes
EPSII 59:006 Spring 2004.
Module 12 Input and Output
ETE 132 Lecture 8 By Munirul Haque.
EECE.2160 ECE Application Programming
Chapter 11 Files chap8.
CSc 352 File I/O Saumya Debray Dept. of Computer Science
EECE.2160 ECE Application Programming
Professor Jodi Neely-Ritz University of Florida
Presentation transcript:

1 Lecture09: Global Variables, File I/O, and Variable-Length Arguments 5/16/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C

Administration Assignment #8 is on the course homepage and due 5/23. 2

Four Items Global vs. local variables File I/O Variable length arguments 3

Local vs. Global Variables The scope of a declaration is the block of code where the variable is valid for use. A global variable(declaration) is outside the main program. –Normally grouped with other global declarations and at the beginning of the program file. A local variable (declaration) is inside the body of a function. –Locally declared variables cannot be accessed outside of the function they were declared in. –Possible to declare the same identifier name in different parts of the program. 4

Example int y = 38; // global variable double x; void f(int, int); void main( ) { int z=47; // local variable while(z<400) { int a = 90; z += a++; z++; } y = 2 * z; f(1, 2); } void f(int s, int t) { int r = 12; int z = 27; s = r + t + y; s += z; } 5

Global Variables Undisciplined use of global variables may lead to confusion and debugging difficulties. –Example? Instead of using global variables in functions, try passing local variables by reference.

File I/O Before a file can be read or written, it has to be opened by the library function fopen. fopen takes an external name like data.txt, does some housekeeping and negotiation with the operating system, and returns a pointer to be used in subsequent reads or writes of the file. This pointer points to a structure FILE. FILE *fp;

fopen FILE *fopen(char *name, char *mode); void fclose(FILE* stream) fopen returns a pointer to a FILE. FILE is a type name. It is defined with a typedef. mode can be –r - read –w - write –a - append –a “b” can be appended to the mode string to work with binary files. For example, “rb” means reading binary file.

Text Files - fprintf and fscanf int fprintf(FILE *fp, char *format,...); int fscanf(FILE *fp, char *format,...); int feof(FILE *fp); // return 1/0 end-of-file is reached Similar to printf and scanf.

Example – create and write to a file #include int main() { FILE *fp; char name[10]; double balance; int account; if ((fp = fopen(“clients.dat”, “w”)) == null) { printf(“File could not be opened\n”); } else { printf(“Enter one account, name, and balance.\n”); scanf(“%d%s%lf”, &account, name, &balance); fprintf(fp, "%d %s %.2f\n", account, name, balance); fclose(fp); } return 0; }

Example – read from a file #include int main() { FILE *fp; char name[10]; double balance; int account; if ((fp = fopen(“clients.dat”, “r”)) == null) { printf(“File could not be opened\n”); } else { fscanf(fp, “%d%s%lf”, &account, name, &balance); printf("%d %s %.2f\n", account, name, balance); fclose(fp); } return 0; }

Binary Files - fread and fwrite size_t fread(void *array, size_t size, size_t count, FILE *fp); size_t fwrite(void *array, size_t size, size_t count, FILE *fp); array must be a pointer size - size of elements in this array count - number of elements in this array

Example #include int main() { FILE *fp; float value[3]; fp = fopen(“account.txt”, "rb"); fread(value, sizeof(float), 3, fp); printf("%f\t%f\t%f\n", value[0], value[1], value[2]); fclose(fp); return 0; }

Example #include int main() { FILE *fp; float value[3] = {1.0, 2.0, 3.0}; fp = fopen(“account.txt”, “wb"); fwrite(value, sizeof(float), 3, fp); fclose(fp); return 0; }

Example #include int main() { FILE *fp; float value[300] = {1.0, 2.0, 3.0}; fp = fopen(“account.txt”, “wb"); fprintf(fp, “%lf %lf %lf\n”, value[0], value[1], value[2], …); // fwrite(value, sizeof(float), 300, fp); fclose(fp); return 0; }

getchar() & putchar() #include int main() { int c; while ((c = getchar()) != EOF) { putchar(tolower(c)); } return 0; }

Table 7.1. ctype.h character-testing functions. NameTrue If Argument Is isalnum()Alphanumeric (alphabetic or numeric) isalpha()Alphabetic iscntrl()A control character, such as Ctrl+B isdigit()A digit isgraph()Any printing character other than a space islower()A lowercase character isprint()A printing character ispunct()A punctuation character (any printing character other than a space or an alphanumeric character) isspace()A whitespace character: space, newline, formfeed, carriage return, vertical tab, horizontal tab, or, possibly, other implementation-defined characters isupper()An uppercase character isxdigit()A hexadecimal-digit character Table 7.2. ctype.h character-mapping functions. NameAction tolower()If the argument is an uppercase character, returns the lowercase version; otherwise, just returns the original argument toupper()If the argument is a lowercase character, returns the uppercase version; otherwise, just returns the original argument includes many useful functions. The argument for these functions is a single char.

Variable-length Argument Lists Let's implement a minimal version of printf. Use “...” to indicate that the number and types of these arguments may vary. The declaration “...” can only appear at the end of an argument list. void minprintf(char *format,...)

What Do We Need? type va_list - declare a variable that will refer to each argument in turn, assume ap macro va_start - initialize ap to point to the rst unnamed argument function va_arg - Each call of va_arg returns one argument and steps ap to the next; va_arg uses a type name to determine what type to return and how big a step to take. function va_end - do whatever cleanup is necessary. It must be called before the program returns.

#include void minprintf(char *format,...) { va_list ap; // points to each unnamed arg in turn char *p, *sval; int ival; va_start(ap, format); // make ap point to 1st unnamed arg for (p = format; *p; ++p) { if (*p != '%') { putchar(*p); continue; } switch (*++p) { case 'd': ival = va_arg(ap, int); printf("%d", ival); break; case 's': for (sval = va_arg(ap, char *); *sval; ++sval) { putchar(*sval); } break; default: putchar(*p); } va_end(ap); // clean up when done }

What Do We Need? type va_list - declare a variable that will refer to each argument in turn, assume ap macro va_start - initialize ap to point to the rst unnamed argument function va_arg - Each call of va_arg returns one argument and steps ap to the next; va_arg uses a type name to determine what type to return and how big a step to take. function va_end - do whatever cleanup is necessary. It must be called before the program returns.