C: Primer and Advanced Topics

Slides:



Advertisements
Similar presentations
C: Advanced Topics-II Winter 2013 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University.
Advertisements

A C++ Crash Course Part II UW Association for Computing Machinery Questions & Feedback.
Using Files Declare a variable, called file pointer, of type FILE * Use function fopen to open a named file and associate this file with the file pointer.
Files in C Rohit Khokher.
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.
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.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Introduction Data files –Can be created, updated,
C Language Summary HTML version. I/O Data Types Expressions Functions Loops and Decisions Preprocessor Statements.
Engineering H192 - Computer Programming The Ohio State University Gateway Engineering Education Coalition Lect 6P. 1Winter Quarter I/O in C Lecture 6.
C Programming. C vs C++ C syntax and C++ syntax are the same but... C is not object oriented * There is no string class * There are no stream objects.
Console and File I/O - Basics Rudra Dutta CSC Spring 2007, Section 001.
An Introduction to C Programming (assuming that you already know Java; this is not an introduction to C++)
Files Programs and data are stored on disk in structures called files Examples Turbo C++ - binary file Word binary file lab1.c - text file lab1.data.
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.
Lone Leth Thomsen Input / Output and Files. April 2006Basis-C-8/LL2 sprintf() and sscanf() The functions sprintf() and sscanf() are string versions of.
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.
File Handling In C By - AJAY SHARMA. We will learn about- FFile/Stream TText vs Binary Files FFILE Structure DDisk I/O function OOperations.
 2007 Pearson Education, Inc. All rights reserved C File Processing.
Characters and Strings File Processing Exercise C Programming:Part 3.
File IO and command line input CSE 2451 Rong Shi.
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.
Fundamental Data Types, Operators and Expressions Kernighan/Ritchie: Kelley/Pohl: Chapter 2 Chapter 2, 3.
Chapter 11: Data Files and File Processing Files and streams Creating a sequential access file Reading data from a sequential access file Using fgetc()
GAME203 – C Files stdio.h C standard Input/Output “getchar()”
Gramming An Introduction to C Programming (assuming that you already know Java; this is not an introduction to C++)
Files A collection of related data treated as a unit. Two types Text
C is a high level language (HLL)
 2007 Pearson Education, Inc. All rights reserved. 1 C File Processing.
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.
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.
 2007 Pearson Education, Inc. All rights reserved C File Processing.
6/9/2016Course material created by D. Woit 1 CPS 393 Introduction to Unix and C START OF WEEK 10 (C-4)
Real Numbers Device driver process within the operating system that interacts with I/O controller logical record 1 logical record 2 logical record 3.
An Introduction to C Programming (assuming that you already know Java; this is not an introduction to C++)
A bit of C programming Lecture 3 Uli Raich.
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.
TMF1414 Introduction to Programming
File Access (7.5) CSE 2031 Fall July 2018.
Day 02 Introduction to C.
An Introduction to C Programming
Chapter 18 I/O in C.
File I/O.
CSC215 Lecture Input and Output.
Plan for the Day: I/O (beyond scanf and printf)
BY GAWARE S.R. COMPUTER SCI. DEPARTMENT
C Programming:Part 3 Characters and Strings File Processing Exercise.
Instructor: Ioannis A. Vetsikas
CS111 Computer Programming
File Input/Output.
Programming in C Input / Output.
Programming in C Input / Output.
Chapter 11 – File Processing
I/O in C Lecture 6 Winter Quarter Engineering H192 Winter 2005
Beginning C Lecture 11 Lecturer: Dr. Zhao Qinpei
Text and Binary File Processing
File Input and Output.
File Handling.
Chapter: 7-12 Final exam review.
Programming Assignment #1 12-Month Calendar—
Fundamental of Programming (C)
Programming in C Input / Output.
C Input / Output Prabhat Kumar Padhy
Module 12 Input and Output
Programming Languages and Paradigms
C Language B. DHIVYA 17PCA140 II MCA.
Professor Jodi Neely-Ritz University of Florida
INTRODUCTION TO C.
Presentation transcript:

C: Primer and Advanced Topics

Style Basics: comments white space modularity Naming conventions: variableNames ("Hungarian Notation": m_pMyInt, bDone) FunctionNames tTypeDefinitions CONSTANTS

Brace Styles K&R: if (total > 0) { printf( “Pay up!” ); total = 0; } else { printf( “Goodbye” ); } non-K&R: if (total > 0) { printf("Pay up!"); total = 0 ; } else { printf("Goodbye"); }

Variables and Storage Syntax: <type> <varName> [= initValue]; Types (incomplete list): char short int long float double all can be: signed (default) or unsigned

Operators Arithmetic Operators: *, /, +, -, % Relational Operators: <, <=, >, >=, ==, != Assignment Operators: =, +=, -=, *=, /=, ++, -- don’t abuse these, ie: o = --o - o--; Logic Operators: &&, ||, ! Bitwise Operators: &, |, ~, >>, <<

Arrays Arrays start at ZERO! (a mistake you will make often, trust me) Arrays of int, float, etc. are pretty intuitive int months[12]; float scores[30]; Strings are arrays of char (C’s treatment of strings is not so intuitive) see Wang, Appendix 12 for string handling functions Multi-dimensional arrays: int matrix[2][4]; (not matrix[2,4])

Decision and Control if( condition ) statement; else while( condition ) statement for( initial; condition; iteration ) do break and continue useful inside loops

Decision and Control (cont) switch ( expression ) case constant1: statement; break; case constant2: default:

Scope Scopes are delimited with curly braces “{” <scope> “}” New scopes can be added in existing scopes Child scopes inherit visibility from parent scope Parent scope cannot see into child scopes Outermost scopes are all functions These scope rules are all similar to those of Turing and other common programming languages

Functions Definition: <type> <functionName> ( [type paramName], ... ) No “procedures” in C … only functions Every function should have a prototype Example: float area( float width, float height ); float area( float width, float height ) { return( width * height ); }

Preprocessor #include (<file.h> versus “file.h”) #define (constants as well as macros) #ifdef (useful for debugging and multi-platform code) statements #else #endif

Structs struct [<structureName>] { <fieldType> <fieldName>; } [<variableName>]; structureName and variableName are optional, but should always have at least one, otherwise it’s useless (can’t ever be referenced) Example: struct int quantity; char name[80]; } inventoryData;

Typedefs and Enumerated Types typedef <typeDeclaration>; Example: typedef int tBoolean; tBoolean flag; enum <enumName> { tag1, tag2, ... } <variableName> enum days { SUN, MON, TUE, WED, THU, FRI, SAT }; enum days today = MON; or typedef enum { SUN, MON, TUE } tDay; tDay today = MON;

Pointers A pointer is a type that points to another type in memory Pointers are typed: a pointer to an int is different than a pointer to a long An asterisk before a variable name in its declaration makes it a pointer i.e.: int *currPointer; (pointer to an integer) i.e.: char *names[10]; (an array of char pointers) An ampersand (&) gives the address of a pointer i.e.: currPtr = &value; (makes currPtr point to value) An asterisk can also be used to de-reference a pointer i.e.: currValue = *currPtr;

Pointers (cont) Use brackets to avoid confusion: ie: *(currPtr++); is very different from (*currPtr)++; Using ++ on a pointer will increment the pointer’s address by the size of the type pointed to You can use pointers as if they were arrays (in fact, arrays are implemented a pointers)

Command Line Arguments int main( int argc, char *argv[] ) { . . . argc is the number of arguments on the command line, including the program name The array argv contains the actual arguments Example: if( argc == 3 ) printf( “file1:%s file2:%s\n”, argv[1], argv[2] );

Casting You can force one type to be interpreted as another type through casting, ie: someSignedInt = (signed int) someUnsignedInt; Be careful, as C has no type checking, so you can mess things up if you’re not careful NULL pointer should always be cast, ie: (char *) NULL, (int *) NULL, etc.

Library Functions for I/O

Opening and Closing Files (10.2) FILE *fp; fp = fopen( fileName, “r” ); fclose( fp ); fp is of type “FILE*” (defined in stdio.h) fopen returns a pointer (or NULL if unsuccessful) to the specified fileName with the given permissions: “r” read “w” write (create new, or wipe out existing fileName) “a” append (create new, or append to existing fileName) “r+” read and write

Character-by-Character I/O fgetc( fp ) # returns next character from files referenced by fp getc( fp ) # same as fgetc, but implemented as a macro getchar() # same as getc( stdin ) These return the constant “EOF” when the end-of-file is reached fputc( c, fp ) # outputs character c to file referenced by fp putc( c, fp ) # same as fputc, but implemented as a macro putchar( c ) # same as putc( c, stdout )

Line-by-Line Input fgets( data, size, fp ) # read next line from fp (up to size) gets( data ) # read next line from stdin fgets() is preferable to gets() Returns address of data array (or NULL if EOF or other error occurred) Example: #define MAX_LENGTH 256 char inputData[MAX_LENGTH]; FILE *fp; fp = fopen( argv[1], “r” ); fgets( inputData, MAX_LENGTH, fp );

Line-by-Line Output fputs( data, fp ) # prints string “data” on stream referenced by fp puts( data ) # same as fputs( data, stdout ) except a newline is automatically appended

Formatted Output printf( fmt, args ... ) fprintf( fp, fmt, args ... ) sprintf( string, fmt, args ... ) Examples: fprintf( stderr, “Can’t open %s\n”, argv[1] ); sprintf( fileName, “%s”, argv[1] ); sprintf example above better achieved with “strcpy()” function K&R book or man pages for all the details

Formatted Input scanf( fmt, *args ... ) fscanf( fp, fmt, *args ... ) sscanf( string, fmt, *args ... ) Examples: fscanf( fp, “%s %s”, firstName, lastname ); sscanf( argv[1], “%d %d”, &int1, &int2 ); Returns number of successful args matched … be careful, scanf should only be used in limited cases where exact format is know in advance See K&R book or man pages for all the details

Binary I/O fread( buf, size, numItems, fp ) fwrite( buf, size, numItems, fp ) Examples: fread( readBuf, sizeof( char ), 80, stdin ); fwrite( writeBuf, sizeof(struct utmpx), 1, fp ); Returns number of successful items read or written Other functions: rewind(fp); fseek(fp, offset, kind); ftell(fp);