Command Line arguments Main function: int main(argc, char *argv[]) –argc is the count of command line arguments –argv is an array of strings argv[0] is.

Slides:



Advertisements
Similar presentations
Lecture 3 Some commonly used C programming tricks. The system command Project No. 1: A warm-up project.
Advertisements

C: Advanced Topics-II Winter 2013 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University.
1 Chapter 10 Strings and Pointers. 2 Introduction  String Constant  Example: printf(“Hello”); “Hello” : a string constant oA string constant is a series.
Character String Manipulation. Overview Character string functions sscanf() function sprintf() function.
Lecture 20 Arrays and Strings
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
Unix Continuum of Tools Do something once: use the command line Do something many times: –Use an alias –Use a shell script Do something that is complex.
Functions Definition: Instruction block called by name Good design: Each function should perform one task and do it well Functions are the basic building.
. Plab – Tirgul 4 structs & arrays, file I/O, debugging memory errors.
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++)
CMSC 104, Version 8/061L18Functions1.ppt Functions, Part 1 of 4 Topics Using Predefined Functions Programmer-Defined Functions Using Input Parameters Function.
CPSC 441 Tutorial TA: Fang Wang Introduction to C.
University of Washington CSE 351 : The Hardware/Software Interface Section 5 Structs as parameters, buffer overflows, and lab 3.
University of Calgary – CPSC 441. C PROGRAM  Collection of functions  One function “main()” is called by the operating system as the starting function.
Unix Makefiles COP 3330 Lecture Notes Dr. David A. Gaitros.
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.
Parsing and Validating Text Input file opening and closing fprintf, fscanf and sscanf fgets and fputs fgetc and putc Parsing a Token Delimited Input Record.
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.
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.
C Programming in Linux Jacob Chan. C/C++ and Java  Portable  Code written in one system and works in another  But in C, there are some libraries that.
File IO and command line input CSE 2451 Rong Shi.
Current Assignments Start Reading Chapter 6 Project 3 – Due Thursday, July 24 Contact List Program Homework 6 – Due Sunday, July 20 First part easy true/false.
1 COMP 2130 Introduction to Computer Systems Computing Science Thompson Rivers University.
Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee C Language Part 4.
File I/O, Project 1: List ADT Bryce Boe 2013/07/02 CS24, Summer 2013 C.
CPS4200 Unix Systems Programming Chapter 2. Programs, Processes and Threads A program is a prepared sequence of instructions to accomplish a defined task.
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:
Exam / Homework Exam 1 Starting K&R chapter 4 tonight
C By Example 1 The assumption is that you know Java and need to extend that knowledge so you can program in C. 1. Hello world 2. declarations 3. pass by.
(language, compilation and debugging) David 09/16/2011.
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.
Chapter 11: Data Files and File Processing Files and streams Creating a sequential access file Reading data from a sequential access file Using fgetc()
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.
Lecture 11: Files & Arrays B Burlingame 18 November 2015.
Gramming An Introduction to C Programming (assuming that you already know Java; this is not an introduction to C++)
Today’s Material Strings Definition Representation Initialization
CS 1704 Introduction to Data Structures and Software Engineering.
Files A collection of related data treated as a unit. Two types Text
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.
IO revisited CSE 2451 Rong Shi. stdio.h Functions – printf – scanf(normally stops at whitespace) – fgets – sscanf Standard streams – stdin(defaults to.
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.
6/9/2016Course material created by D. Woit 1 CPS 393 Introduction to Unix and C START OF WEEK 10 (C-4)
C Tutorial - Pointers CS 537 – Introduction to Operating Systems.
An Introduction to C Programming (assuming that you already know Java; this is not an introduction to C++)
Hank Childs, University of Oregon April 15 th, 2016 CIS 330: _ _ _ _ ______ _ _____ / / / /___ (_) __ ____ _____ ____/ / / ____/ _/_/ ____/__ __ / / /
 Dynamic Memory Allocation  Linked Lists  void main() {{ ◦ FILE *file; ◦ char file_name[] = “file.txt”; ◦ if ((file = fopen(file_name, "w")) ==
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.
An Introduction to C Programming
CSE 303 Concepts and Tools for Software Development
CSC215 Lecture Input and Output.
Plan for the Day: I/O (beyond scanf and printf)
C Basics.
Computer Science 210 Computer Organization
CS111 Computer Programming
Computer Science 210 Computer Organization
CSE1320 Files in C Dr. Sajib Datta
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.
File Input and Output.
File Handling.
File I/O & UNIX System Interface
CS1100 Computational Engineering
I/O CS580U - Fall 2018.
Professor Jodi Neely-Ritz University of Florida
Presentation transcript:

Command Line arguments Main function: int main(argc, char *argv[]) –argc is the count of command line arguments –argv is an array of strings argv[0] is the name of the program argv[1] is the first argument from the command line argv[k] is the k th argument from the command line Command line example: >prog 123 abc –argc = 3 –argv[0] = "prog", argv[1] = "123", argv[2] = "abc" If you expect two arguments: if (argc!=3) {printf("usage: prog ); exit(1); }

Inputting Problem scanf – User can crash the program by typing too much fgets – User cannot crash the program Example #include int main(void) { char input[10+1]; char *result; printf("Enter some text:\n"); result = fgets(input, sizeof(input), stdin); if (result != NULL) printf("You entered: %s", result); else printf("Error processing fgets()\n"); return 0; }

typedef typedef assigns a label to a declaration Syntax: typedef label; Then you can declare using the label Examples: –Declare a new type typedef char * String; typedef int Boolean; –Declare an instance of that type void myFunc(String data, Boolean flag)

struct struct is a collection of data types Example: struct { int age; char name[ ]; float salary; }; Useful to create a new complex type typedef struct { int age; char name[100+1]; float salary; } Person; Instantiate: Person bill; Note: A complex type is like Java class, but without methods

Accessing struct data Declare: Person person[100]; Access fields: JLJ printf("His name is %s\n", person[0].name); for (int i=0; i<100; i++) printf("%s is %d years old with salary %f\n", person[i].name, person[i].age, person[i].salary);

Using pointers for functions void myFunc(const Person first, Person *second) { second->name = first.name; second->age = first.age; second->salary = first.salary; } Note: The arrow indirectly addresses access data in structs Note: Pass by value copies the entire structure to the stack. This can be inefficient, so most programmers always use pointers in functions

Reading a text file #include int main(void) { char data[256]; FILE *file; file = fopen("someFile.txt","r"); if (file==NULL) return 2; while (!feof(file)) { int cSize=sizeof(char); // normally 1 int dSize=sizeof(data); // 256 * cSize int size= dSize/cSize; // Array byte size fgets(data, size,file); printf("%s",data); } fclose(file); return 0; }

Writing to a text file #include int main() { FILE *file; char data[256+1]; fgets(data, sizeof(data), stdin); file = fopen("someFile.txt", "w"); if(file==NULL) { fprintf(stderr, "Can't create output file\n"); return 2; } fprintf(file, "%s\n", data); fclose(file); return 0; } Question: Why not use printf instead of fprintf with stderr

fscanf and fgets to read files fscanf(File *fp, const char *temp, args … ) Works just like scanf but is insecure –Stops on white space –No protection for buffer size Better approach –Use fgets: reads till newline or n-1 characters read –Automatically puts the null at the end of the string –Returns null if error or end of file –If you have to parse, use sscanf after the data is in memory

sscanf Example: char str[] = " "; int a, b, c; if (sscanf(str, "%d %d %d", &a, &b, &c) != 3) fprintf(stderr, "What happened?"); sscanf is a very useful tool for parsing input or data read from files Note: the strstr function is useful for finding the first occurrence of a little string in a big one. See lab 10. char *strstr (const char *haystack, const char *needle);

Buffered Output Data does NOT go dirctly to a file –Why? It is more efficient for the operating system to decide when to write data. –What happens? Data goes to an operating system buffer –When does the data write? When the buffer is full or manually flushed –How does it manually get flushed? Use the call fflush(file); –What about stdout? call fflush(stdout)

Final Notes Portability Operating Systems end lines differently C always uses '\n' to end a line stdio functions translate for the OS in question EOF: stdio functions use this constant #include void main() { int c, nc = 0; while ( (c = getchar()) != EOF ) nc++; printf("Characters in file = %d\n",nc); } GDB: The set args command is useful before running the program. It sets the command line arguments as if you typed them from the command line

Make Utility to build systems composed of many source and data files Purpose –To minimize management errors of incorrect builds made after a minor change –To only compile and build those things that were changed since the previous build –To create source for creating systems geared for certain configurations and locals

Installations Typical installations of applications from source –Obtain tar.gz bundle and uncompress –Execute./configure script to set platform-based parameters. The script may launch a set of C based programs to inquire about the linux configuration –Execute make to compile and create executables The linux command to execute make: –make [-f custom make file] buildType –Note: If no custom make file, the command looks for a file named: makefile –Note: buildType tells the make script the kind of build desired.

Make Command Script Example all: hello hello: main.o factorial.o hello.o g++ main.o factorial.o hello.o -o hello main.o: main.cpp g++ -c main.cpp factorial.o: factorial.cpp g++ -c factorial.cpp hello.o: hello.cpp g++ -c hello.cpp clean: rm -rf *o hello Syntax: target: dependencies [tab] system command Create target if the dependencies are met

Using Make Variables CC=g++ CFLAGS=-c -Wall all: hello hello: main.o factorial.o hello.o $(CC) main.o factorial.o hello.o -o hello main.o: main.cpp $(CC) $(CFLAGS) main.cpp factorial.o: factorial.cpp $(CC) $(CFLAGS) factorial.cpp hello.o: hello.cpp $(CC) $(CFLAGS) hello.cpp clean: rm -rf *o hello Use G++ option flags: compile and all warnings Use g++ for the compiler.

A More Complex Example CC=g++ CFLAGS=-c -Wall LDFLAGS= SOURCES=main.cpp hello.cpp factorial.cpp OBJECTS=$(SOURCES:.cpp=.o) EXECUTABLE=hello all: $(SOURCES) $(EXECUTABLE) $(EXECUTABLE): $(OBJECTS) $(CC) $(LDFLAGS) $(OBJECTS) -o $(CC) $(CFLAGS) $< -o