An Introduction to C Programming (assuming that you already know Java; this is not an introduction to C++)

Slides:



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

Introduction to C Programming
A C++ Crash Course Part II UW Association for Computing Machinery Questions & Feedback.
Unions The storage referenced by a union variable can hold data of different types subject to the restriction that at any one time, the storage holds data.
1 Chapter 10 Strings and Pointers. 2 Introduction  String Constant  Example: printf(“Hello”); “Hello” : a string constant oA string constant is a series.
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.
MPI and C-Language Seminars Seminar Plan (1/3)  Aim: Introduce the ‘C’ Programming Language.  Plan to cover: Basic C, and programming techniques.
C For Java Programmers Tom Roeder CS sp. Why C? The language of low-level systems programming  Commonly used (legacy code)  Trades off safety.
CSSE221: Software Dev. Honors Day 27 Announcements Announcements Projects turned in? Projects turned in? The 2 required Angel surveys are due by 9 pm tonight.
C Language Summary HTML version. I/O Data Types Expressions Functions Loops and Decisions Preprocessor Statements.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
Guide To UNIX Using Linux Third Edition
15213 C Primer 17 September Outline Overview comparison of C and Java Good evening Preprocessor Command line arguments Arrays and structures Pointers.
An Introduction to C Programming (assuming that you already know Java; this is not an introduction to C++)
CPSC 441 Tutorial TA: Fang Wang Introduction to C.
University of Calgary – CPSC 441. C PROGRAM  Collection of functions  One function “main()” is called by the operating system as the starting function.
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.
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.
1 C++ Syntax and Semantics, and the Program Development Process.
C What you Know* Objective: To introduce some of the features of C. This assumes that you are familiar with C++ or java and concentrates on the features.
Characters and Strings File Processing Exercise C Programming:Part 3.
Lecture 3: Getting Started & Input / Output (I/O) “TRON” Copyright 1982 (Walt Disney Productions)
File I/O, Project 1: List ADT Bryce Boe 2013/07/02 CS24, Summer 2013 C.
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process.
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 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:
Introduction to Systems Programming (CS 0449) C Preprocessing Makefile File I/O.
Memory Layout, File I/O Bryce Boe 2013/06/27 CS24, Summer 2013 C.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
An Introduction to MPI (message passing interface)
A Quick Look at C for C++ Programmers Noah Mendelsohn Tufts University Web: COMP.
What we will cover A crash course in the basics of C “Teach yourself C in 21 days”
Lecture 01a: C++ review Topics: Setting up projects, main program Memory Diagrams Variables / Types (some of) the many-types-of-const's Input / Output.
1 CSC103: Introduction to Computer and Programming Lecture No 28.
Pointers & References. Pointers Pointer arithmetic Pointers and arrays Pointer-related typedef’s Pointers and const References.
Java & C++ Comparisons How important are classes and objects?? What mechanisms exist for input and output?? Are references and pointers the same thing??
Gramming An Introduction to C Programming (assuming that you already know Java; this is not an introduction to C++)
Announcements Assignment 1 due Wednesday at 11:59PM Quiz 1 on Thursday 1.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
C is a high level language (HLL)
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.
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.
Real Numbers Device driver process within the operating system that interacts with I/O controller logical record 1 logical record 2 logical record 3.
Hank Childs, University of Oregon April 15 th, 2016 CIS 330: _ _ _ _ ______ _ _____ / / / /___ (_) __ ____ _____ ____/ / / ____/ _/_/ ____/__ __ / / /
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
CSE 374 Programming Concepts & Tools
C Primer.
CSE 374 Programming Concepts & Tools
A bit of C programming Lecture 3 Uli Raich.
Lecture 11 File input/output
An Introduction to C Programming
No Objects, No Type Safety
C Basics.
CS111 Computer Programming
Programming in C Input / Output.
Programming in C Input / Output.
Beginning C/C++ sans objects (That’s French! That’s fancy!
C What you Know* Objective: To introduce some of the features of C. This assumes that you are familiar with C++ or java and concentrates on the features.
Text and Binary File Processing
File Input and Output.
Chapter: 7-12 Final exam review.
Programming in C Input / Output.
Chapter 12: File I/O.
CSc 352 File I/O Saumya Debray Dept. of Computer Science
15213 C Primer 17 September 2002.
Presentation transcript:

An Introduction to C Programming (assuming that you already know Java; this is not an introduction to C++)

Minimal C program int main ( int argc, char** argv ) { return 0; //comment just like Java } Or int main ( int argc, char* argv[] ) { return 0; /* comment just like Java */ } Or (typically, you aren’t going to change them) int main ( const int argc, const char* const argv[] ) { return 0; } What does main look like in Java? What is used as ‘const’ in Java?

Java’s main public static void main ( String args[] ) { }

C vs. Java types C –doesn’t init vars (with a few exceptions) –bool, char, short, int, long –float, double –unsigned char –unsigned short –unsigned int –long long –long double Java –does init vars (specifically objects which are defined to be an instance of a class OR arrays; primitive types are NOT initialized and require initialization) –boolean, byte, short, int, long –float, double

ASCII output in C (using the standard I/O library) #include //needed for defns int main ( int argc, char* argv[] ) { puts( “hello, world.” ); printf( “hello, world.” ); printf( “hello, world.\n” ); return 0; }

ASCII output in C #include //header file w/ definitions int main ( int argc, char* argv[] ) { printf( “hello, %s. \n”, “fred” ); int i = 12; printf( “I am %d years old. \n”, i ); double d = 12.9; printf( “d is equal to %f (d is not equal to %d). \n”, d, d ); return 0; } How can d be both %f and %d?

ASCII file output in C (using the standard I/O library) #include int main ( int argc, char* argc[] ) { //open the file for output (erase anything already there!) FILE* fp = fopen( “fred.dat”, “wb” ); assert( fp!=NULL ); //write to the file fprintf( fp, “hello, world.\n” ); //close the file fclose( fp ); fp = NULL; return 0; } Hint: Always open b/binary or binary I/O will act strangely under Windows.

ASCII file output format specs %d – an int %c – a char %x – an int in hex %f – a double or a float %s – string Many, many, many others and variations.

ASCII file input format specs %d – an int %c – a char %x – an int in hex %f – a float %lf – a double (that’s % ell eff) %s – string Many, many, many others and variations. (see man –s 3c printf)

Binary file output in C We will discuss binary file I/O after we discuss pointers. We will discuss input after we discuss pointers as well.

I/O in C printf, scanf, gets, and puts perform buffered I/O (to stdin and stdout). fopen, fread, fwrite, fprintf, fseek, fscanf, fgets, fputs, and fclose perform buffered I/O. open, read, write, seek, and close perform unbuffered I/O.

C pointers int i=12; –i is a variable. It exists in some memory location. At that memory location is the value of 12. –What is the size of i (in bytes)? printf( “An int is %d bytes. \n”, sizeof(int) ); printf( “i=%d, i occupies %d bytes. \n”, i, sizeof(i) ); –What is the virtual address of i, i.e., where is i in memory?

C pointers Let’s introduce an operator (&) that yields the address of a variable. int i = 12; printf( “the address of i is %d. \n”, &i ); printf( “the address of i is %x. \n”, &i );

C pointers How do we declare variables that hold pointers (instead of values)? int i=12, j=52; int* ptr = &i; //ptr points to i ptr = &j; //ptr now points to j

C pointers Derefencing pointers (getting at what they point to): inti = 12; int*iptr = &i; printf( “i=%d, *iptr=%d. \n”, i, *iptr ); Is *iptr the same as iptr?

C pointers Derefencing pointers (getting at what they point to): inti = 12; int*iptr = &i; *iptr = 52; printf( “i=%d. \n”, i ); //What is i’s value?

C pointers C pointers can be treated as arrays! #define N 100 int ray[ N ];//note: syntax diff java int* ptr = ray;//same as ptr = &ray[0] for (int i=0; i<N; i++) { ptr[i] = 0; //same as ray[i] = 0 }

C pointers C pointers can be treated as arrays. #define N 100 int ray[ N ]; int* ptr = ray; //same as ptr = &ray[0] for (int i=0; i<N; i++) { *ptr = 0; ++ptr; }

C pointers C pointers can be treated as arrays. #define N 100 int ray[ N ]; int* ptr = ray; //same as ptr = &ray[0] for (int i=0; i<N; i++) { *ptr++ = 0; }

C pointers C pointers can be treated as arrays (most of the time). #define N 100 int ray[ N ]; int* ptr = ray; //same as ptr = &ray[0] for (int i=0; i<N; i++) { *ptr++ = 0; } Every time we ++ ptr, how much is added to ptr? 1?

C pointers #include int main ( int argc, char* argv[] ) { int value = 12; int* iptr = &value; printf( "%u \n", iptr ); ++iptr; printf( "%u \n", iptr ); iptr = iptr + 1; printf( "%u \n", iptr ); return 0; } output:

C pointers Common pitfall int* ptr1, ptr2; //what (type) is ptr2?

C pointers Common pitfall int* ptr1, ptr2; This is actually the same as int *ptr1, ptr2; Which means that ptr2 is an int (not an int*)!

C pointers and arrays #define N 100 intray[ N ]; int*ptr = ray; printf( “%d %d \n”, ray[12], ptr[12] ); So, for the most part, pointers and arrays are interchangeable in C.

C pointers and arrays Common pitfall (no array bounds check in C) #define N 100 intray[ N ]; int*ptr = ray; printf( “%d %d \n”, ray[N], ptr[1000] );

C pointers and arrays So why are these, in effect, the same? int main ( int argc, char** argv ) { return 0; } Or int main ( int argc, char* argv[] ) { return 0; }

More C pointers Cast = change from one type to another. double d = 0.7; int i = (int)(d+0.5);//round d int j = (int)d;//don’t round d Sometimes we need to change (cast) from one pointer type to another.

ASCII INPUT

ASCII input Use scanf (from stdin) and fscanf. printf( “enter two integers: “ ); int n1, n2; scanf( “%d %d”, &n1, &n2 ); Why is ‘&’ necessary?

ASCII input Use fscanf to read from ASCII files. FILE* fp = fopen( “input.txt”, “rb” ); assert( fp!=NULL ); int n1, n2; fscanf( fp, “%d %d”, &n1, &n2 ); … How do we know if anything was read?

int scanf ( const char *format,... ); int fscanf ( FILE *stream, const char *format,... );

ASCII input Use fscanf to read from ASCII files. FILE* fp = fopen( “input.txt”, “rb” ); assert( fp!=NULL ); int n1, n2, count; count = fscanf( fp, “%d %d”, &n1, &n2 ); if (count != 2) { … }

Notes about I/O stdin, stdout, and stderr are predefined for you and available for every program to use. –You do not need to define them and you should not open them. –They are already defined for you when you #include.

More notes about I/O fprintf( stdout, “hello \n” ); is the same as printf( “hello \n” ); scanf( “%d”, &n1 ); is the same as fscanf( stdin, “%d”, &n1 );

More notes about I/O Read in a line of input. char *gets ( char *s ); char *fgets ( char *s, int size, FILE *stream ); What’s the difference between: char buff[ 255 ]; gets( buff ); fgets( buff, sizeof(buff), stdin );

DYNAMIC MEMORY ALLOCATION

More C pointers Dynamic memory allocation (and deallocation). –malloc int* iptr = (int*)malloc( 10*sizeof(int) ); assert( iptr!=NULL ); –free free( iptr ); iptr = NULL; //good idea, not required Must #include at top. cast

BINARY I/O

Binary I/O Buffered –fread and fwrite Unbuffered –read and write –We will skip unbuffered I/O (but you are free to use it).

Binary input: fread size_t fread ( void* ptr, size_t size, size_t nitems, FILE* stream ); Returns nitems if OK. FILE* fp = fopen( “junk.in”, “rb” ); #define N 100 int buffer[ N ]; int k = fread( buffer, sizeof( int ), N, fp ); What is k?

Binary input: fread size_t fread ( void* ptr, size_t size, size_t nitems, FILE* stream ); Returns nitems if OK. #define N 100 int buffer[ N ]; int k = fread( buffer, sizeof( int ), N, fp ); k = fread( buffer, 1, sizeof( buffer ), fp ); k = fread( buffer, sizeof( buffer ), 1, fp );

Binary input: fread int buffer[ N ]; int k = fread( buffer, 1, sizeof( buffer ), fp ); k = fread( buffer, sizeof( buffer ), 1, fp ); This (sizeof(buffer)) is an example of where arrays and pointers are NOT the same in C.

Binary output: fwrite size_t fwrite ( void* ptr, size_t size, size_t nitems, FILE* stream ); Returns nitems if OK. FILE* fp = fopen( “junk.in”, “wb” ); #define N 100 int buffer[ N ]; int k = fwrite( buffer, sizeof( int ), N, fp ); What is k?

0utput in C (using the standard C++ library) #include using namespace std; int main ( int argc, char* argc[] ) { cout << “hello, world.” << endl; return 0; } You are free to use the standard C++ library but we won’t discuss it in this class.

MISC

C structures Collection of data (only). –precursor to object –similar to a FORTRAN record Especially useful for message passing. –Ex. { do this operation, here is the data }

C structures struct message { enum {OP_CALCULATE, OP_RESULT, OP_EXIT }; intoperation; intparameters[100]; doubleresult; }; Tip: don’t forget ; at end.

C structures int main ( int argc, char* argv[] ) { struct message m; m.operation = m.OP_CALCULATE; return 0; }

C structures (w/ pointers) int main ( int argc, char* argv[] ) { struct message* m; m = (struct message*) malloc (sizeof(struct message) ); assert( m!=NULL ); m->operation = m->OP_CALCULATE; //most often used (*m).operation = (*m).OP_CALCULATE; //same thing return 0; } Why not sizeof(struct message*)?

C++ classes (not required for this course) class Simple3D : public DistanceTransform3D { public: //define public members (data) and methods (functions) here. private:. protected:. };

Useful header files #include

Compiling C/C++ programs on Linux g++ compiles both C and C++ –Always use g++ for C or C++. Don’t use gcc. It only compiles C and C programs that compile with gcc may not compile with g++. g++ won’t compile 1978 K&R C code but you shouldn’t be coding in that anyway. File name extensions –Always use.cpp for C or C++ code files. (Don’t use.c. It is only for C programs which may compile with gcc but not with g++.) Enter ‘man g++’ for help.

Compiling and running C programs on Linux g++ command options -g, -O, -O2, -O3 Optimization level – debug to optimized. -Wall Issue warnings for questionable code. -c Compile (making a.o file) but don’t link. -o Specify output file name. -l (el=lower case L) Specify link library name. Note: use mpic++ (not currently installed on brunel) to compile mpi-based C/C++ programs.

Example of compiling C programs g++ junk.cpp Compile and link producing a.out. g++ -c junk.cpp Compile (but don’t link) producing junk.o. g++ -o junk.exe junk.o Link junk.o and produce junk.exe. g++ -o junk.exe junk.cpp Compile and link producing junk.exe.

Example of compiling C programs g++ -g -o junk.exe junk.cpp Compile and link producing junk.exe w/ debug information. g++ -O3 -o junk.exe junk.cpp Compile and link producing an optimized version called junk.exe. g++ -O -o fred.exe junk1.cpp junk2.o \ junk3.cpp -lm Compile junk.1pp and junk3.cpp (but not junk2.o) and link producing fred.exe which is somewhat optimized and linked to the math library.

Handling C command line arguments argc –count/number of arguments argv –array of strings (the actual arguments) Java doesn’t have argc. Why? In Java, argv[0] is the first argument. In C, argv[0] is the name of the program/command and argv[1] is the first argument.

End of C for Java programmers