6/9/2016Course material created by D. Woit 1 CPS 393 Introduction to Unix and C START OF WEEK 10 (C-4)

Slides:



Advertisements
Similar presentations
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.
Advertisements

Chapter 11: Data Files & File Processing In this chapter, you will learn about Files and streams Creating a sequential access file Reading data from a.
FILES Files types and operations. Files Files are used to store data Data can be Text (ASCII only: 0  127) Binary (Full range: 0  256) Each file resides.
Chapter 11 C File Processing Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
Console and File I/O - Basics Rudra Dutta CSC Spring 2007, Section 001.
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.
File Handling Spring 2013Programming and Data Structure1.
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.
 2007 Pearson Education, Inc. All rights reserved C File Processing.
CGS 3460 More On File IO. CGS 3460 What is a File n A file is a package of information with a name attached to it. n Files are used for various purposes:
Characters and Strings File Processing Exercise C Programming:Part 3.
1. Introduction File Declaration and Initialization Creating and Opening File Closing File EOF Reading from and Writing into a File Extra : Random Access.
File IO and command line input CSE 2451 Rong Shi.
Chapter 8 File-Oriented Input and Output. 8.1 INTRODUCTION a file can also be designed to store data. We can easily update files, A data file as input.
Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee C Language Part 4.
CSEB114: Principle of programming Chapter 11: Data Files & File Processing.
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:
1 Lecture09: File I/O 11/19/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to 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.
FILE IO in ‘C’ by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile
24-2 Perform File I/O using file pointers FILE * data-type Opening and closing files Character Input and Output String Input and Output Related Chapter:
GAME203 – C Files stdio.h C standard Input/Output “getchar()”
Files A collection of related data treated as a unit. Two types Text
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.
1 Computer Programming Lecture 15 Text File I/O Assist. Prof Dr. Nükhet ÖZBEK Ege University Department of Electrical&Electronics Engineering
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.
UniMAP SemI-11/12EKT120: Computer Programming1 Files.
ECE 103 Engineering Programming Chapter 29 C Strings, Part 2 Herbert G. Mayer, PSU CS Status 7/30/2014 Initial content copied verbatim from ECE 103 material.
UniMAP SemI-11/12EKT120: Computer Programming1 Files.
Real Numbers Device driver process within the operating system that interacts with I/O controller logical record 1 logical record 2 logical record 3.
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.
Lecture 11 File input/output
File I/O.
CSC215 Lecture Input and Output.
Plan for the Day: I/O (beyond scanf and printf)
C Programming:Part 3 Characters and Strings File Processing Exercise.
CS111 Computer Programming
CSE1320 Files in C Dr. Sajib Datta
CSE1320 Files in C Dr. Sajib Datta
Programming in C Input / Output.
Programming in C Input / Output.
CSE1320 Files in C Dr. Sajib Datta
File I/O We are used to reading from and writing to the terminal:
CSC215 Lecture Input and Output.
CSE1320 Strings Dr. Sajib Datta
Beginning C Lecture 11 Lecturer: Dr. Zhao Qinpei
FILE HANDLING IN C.
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
Command Line Parameters
File Input and Output.
File Handling.
Programming in C Input / Output.
File Handling in C.
Module 12 Input and Output
File I/O & UNIX System Interface
CS1100 Computational Engineering
CSc 352 File I/O Saumya Debray Dept. of Computer Science
Professor Jodi Neely-Ritz University of Florida
I/O CS580U - Fall 2018.
File I/O We are used to reading from and writing to the terminal:
Files Chapter 8.
Presentation transcript:

6/9/2016Course material created by D. Woit 1 CPS 393 Introduction to Unix and C START OF WEEK 10 (C-4)

6/9/2016Course material created by D. Woit 2 Command line Processing main is a function--so OS can pass arguments to it using –Argument Vector, and –Argument Count int main(int argc, char *argv[]) suppose -make executable cla from cla.c: gcc -o cla cla.c -and execute as: cla abc "de f" 74 -then inside cla.c: argc is 4 // # args + 1 (#elts in argv) argv[0] is "cla" // program name argv[1] is "abc" // argument 1 argv[2] is "de f" // argument 2 argv[3] is "74" // argument 3

6/9/2016Course material created by D. Woit 3 Command line Processing Program could print its COMMAND LINE ARGUMENTS as follows: int main (int argc, char *argv[]) { int i; for (i=1; i<argc; i++) printf("command line argument %d is: %s\n", i, argv[i]); printf("Name of program is: %s\n", argv[0]); exit(0); }

6/9/2016Course material created by D. Woit 4 /*Source: suma.c Purpose: to sum the integers supplied on the command line Input: any number of integers in command line Output: the sum of the inputted numbers */ #include int main (int argc, char *argv[]) { int i, /*for loop index*/ sum=0; /*the sum of the arguments*/ for (i=1; i<argc; i++) { sum = sum + atoi(argv[i]); } printf("Sum of the %d integers is %d\n", argc-1, sum); exit(0); } HMWK: Fix suma.c so that it checks for good integer input

6/9/2016Course material created by D. Woit 5 /*Source: cml2.c Purpose: print max of 2 int arguments */ #define GoodInput 0 #define BadInput 1 #include int main (int argc, char *argv[]) { if (argc != 3 ) { fprintf(stderr, "Usage: %s int1 int2\n", argv[0]); exit(BadInput); } if (atoi (argv[1]) > atoi (argv[2]) ) fprintf(stdout, "%s\n", argv[1]); else fprintf(stdout, "%s\n", argv[2]); exit(GoodInput); } Note that functions strtof/strtod etc convert string to float/double etc

6/9/2016Course material created by D. Woit 6 File I/O already used fprintf/fputs to print to FILE stdout, stderr fprintf(stderr, "bad input: %d\n", x); Others: fscanf (fp, str, length) fgetc (fp); fputc (ch, fp) fgets (str, length, fp); fputs (str, fp);

6/9/2016Course material created by D. Woit 7 File I/O Open file named myfile for reading: FILE *fp; // FILE in stdio.h if ( (fp = fopen("myfile","r")) == NULL ) { fprintf(stderr,"fopen: Error opening file\n"); exit(1); } fscanf(fp, "%d", &i); Mode ---- r open text file for read w open text file for write a append to text file r+ open text file for r/w w+ create t.f. for r/w a+ append or create for r/w Note: w & w+: if file not exist, created if it exists, it is destroyed & new created

6/9/2016Course material created by D. Woit 8 Closing a file fclose(fp); 0 if successful EOF if not (exit *should* close all files before pgm termination). fgetc(fp); returns: char read if succ (cast to int) EOF otherwise fputc(ch,fp); returns: char written if succ (cast to int) EOF otherwise

6/9/2016Course material created by D. Woit 9 Example /*Source cio.c Purpose: write a string to file myfile */ #include #define GOOD 0 #define BAD 1 int main(void) { char str[40] = "String to write onto disk"; FILE *fp; char ch, *p; if ((fp = fopen("myfile","w"))==NULL) { fprintf(stderr,"fopen: Cannot open file\n"); exit(BAD); }

6/9/2016Course material created by D. Woit 10 p=str; while (*p) if (fputc(*p++,fp)==EOF) { fprintf(stderr,"fuptc: Error writing file\n"); fclose(fp); /*good form*/ exit(BAD); } fclose(fp); /*good form*/ exit(GOOD); }

6/9/2016Course material created by D. Woit 11 Example /*Source: cio2.c Purpose: display contents of myfile on stdout */ #include #define GOOD 0 #define BAD 1 int main(void) { FILE *fp; int ch; if ((fp=fopen("myfile", "r"))==NULL) { fprintf(stderr,"fopen: Cannot open file\n"); exit(BAD); } while (( ch = fgetc(fp)) != EOF) fputc(ch,stdout); fclose(fp); exit(GOOD); }

6/9/2016Course material created by D. Woit 12 HMWK: Modify cio2.c to turn it into a simple version of unix utility "cat". If no cmd-line input, prints stdin on stdout. If cmd-line inputs (files), print each on stdout

6/9/2016Course material created by D. Woit 13 /*Source: copy.c Purpose: copy file f1 to file f2 Usage: copy f1 f2 */ #include #define GOOD 0 #define BAD 1 int main (int argc, char *argv[]) { FILE *f1, *f2; int ch; if (argc != 3) { fprintf(stderr, "Usage: %s \n",argv[0]); exit(BAD); }

6/9/2016Course material created by D. Woit 14 if ((f1=fopen(argv[1],"r"))==NULL) { fprintf(stderr, "Cannot open %s\n",argv[1]); exit(BAD); } if ((f2=fopen(argv[2],"w"))==NULL) { fprintf(stderr, "Cannot open %s\n",argv[2]); exit(BAD); } while ((ch=fgetc(f1)) != EOF) fputc(ch,f2); fclose(f1); fclose(f2); exit(GOOD); }

6/9/2016Course material created by D. Woit 15 file i/o fgetc() returns EOF if 1) error in reading 2) hits EndOfFile can test for these separately feof(fp) non-0 if at EOF 0 otherwise ferror(fp) non-0 if error reading file 0 otherwise while (!feof(f1)) { ch=fgetc(f1); if (ferror(f1)) { fprintf(stderr, "Error reading... exit(BAD); } if (!feof(f1)) fputc(ch,f2); if (ferror(f2)) { fprintf(stderr, "Error writing... exit(BAD); }

6/9/2016Course material created by D. Woit 16 fgets(str, length, fp); gets chars from FILE fp and stores them in array str, until 1. '\n' read (and transfered to s) 2. (length-1) chars have been read, or 3. EOF returns ptr to str if successful NULL ptr otws Note: -fp could be stdin -the file read pointer advanced "length-1" chars in the file. e.g., fgets(X,3,f1); fgets(Y,3,f1); for file with abcde will put "12" in X and "34" in Y fputs(str,fp) writes str to "file" ptd to by fp returns EOF if error; positive int otws

6/9/2016Course material created by D. Woit 17 HMWK 1. Rewrite copy.c using fgets, fputs, feof and ferror assuming max line length in file is 128 chars. HMWK: 1. Write a program named prt.c that reads text from stdin until EOF and prints the number of lines and/or characters that were read in. The program takes one command line argument, which is l or c or b. If the argument is l, the program prints the number of lines, if c, the number of characters, and if b, it prints the number of both lines and chars.

6/9/2016Course material created by D. Woit 18 HMWK 2. Re-write program prt.c above except this time, the program takes 2 arguments, the second argument being the name of a file from which to read the text. Perform *full* error checking. 3. Re-write the above prt.c so that any number of files are processed (number of chars/lines printed for EACH, in order processed.) 4. Use fscanf and fprintf to read a file with 2 columns of integers, such as: and write the sum of each line to another file, e.g, 6 16 The file names are given on the command line

6/9/2016Course material created by D. Woit 19 perror You could also use function perror (print error) instead of fprintf(stderr...); When any system or library function is called *and fails*, its return code (integer) is put in a system variable that perror can access. (clobbered with each failure). perror translates the integer to an (human understandable) phrase and prints on stderr, prefixed by its string argument e.g., FILE *fp; if ( (fp = fopen("myfile","r")) == NULL ) { perror("fopen"); exit(1); }

6/9/2016Course material created by D. Woit 20 perror if "myfile" did not exist, stderr gets: fopen: No such file or directory (most of the built-in C functions use perror) FYI: All the error codes are defined in /usr/include/asm- generic/errno.h This C function perror in section 3 of man pages (man 3 perror)

6/9/2016Course material created by D. Woit 21 Structures Just as we can group items of same type into arrays, We can group items of dissimilar types into: structures struct s-name { type item1; type item2;... type itemN; } ;

6/9/2016Course material created by D. Woit 22 Structures e.g., a struct to describe cars (in struct1.c) struct car { char make[40]; char model[40]; unsigned int year; float price; } ; Then we can declare various variables of type struct car. struct car woit, chan1, chan2; //3 cars

6/9/2016Course material created by D. Woit 23 Assign woit's car: strcpy(woit.make, "Ferrari"); strcpy(woit.model, "F149"); woit.year = 2012; woit.price = ; Read in chan1's car: scanf("%s", chan1.make); //Porsche gets(chan1.model); //Carrera scanf("%u %f", &chan1.year, &chan1.price); // Print woit's car's make: printf("%s",woit.make); //prints Ferrari printf("%c",woit.make[4]); //prints what?

6/9/2016Course material created by D. Woit 24 Typedefs give your own name to any data type typedef short int Sint; int i; Sint j,k;

6/9/2016Course material created by D. Woit 25 Typedefs for structures struct car { char make[40]; char model[40]; unsigned int year; float price; } chan1 ; //chan1 is a variable like woit and chan2 struct car woit; struct car chan2; typedef struct { char make[40]; char model[40]; unsigned int year; float price; } car; //car is a new datatype (such as Sint above) car woit; car chan1, chan2;

6/9/2016Course material created by D. Woit 26 Arrays of structures car (struct car) is now a datatype, therefore, we can create an array of cars struct car chan[4]; /*if no typedef used*/ or car chan[4]; /*if typedef used*/ How do we use arrays of structures? chan's 0th car: chan[0].year = 1932; chan's 3rd car: chan[3].price = ; sizeof(struct car); /*no typedef*/ or sizeof(car); /*typedef*/ returns?

6/9/2016Course material created by D. Woit 27 HMWK: Write a program that reads an input file such as: Each line of the file contains a "complex number". Assume at most MAX=100 numbers are given. The program must create a structure for a complex number, and then store all the complex numbers in an array. (You must have an array of structures.) Then your program should loop through the array from end to front, and print out the complex numbers in it. E.g., your output should look like 8 + 2i i i 1 + 5i on stdout.