structs as arguments

Similar documents
Important Dates. October 27 th Homework 2 Due. October 29 th Midterm

File I/O. Jin-Soo Kim Computer Systems Laboratory Sungkyunkwan University

CS , Spring Sample Exam 3

Operating System Labs. Yuanbin Wu

The course that gives CMU its Zip! I/O Nov 15, 2001

CSC209H Lecture 3. Dan Zingaro. January 21, 2015

Lecture 23: System-Level I/O

File I/O. Dong-kun Shin Embedded Software Laboratory Sungkyunkwan University Embedded Software Lab.

All the scoring jobs will be done by script

Operating System Labs. Yuanbin Wu

CSE 333 SECTION 3. POSIX I/O Functions

Ricardo Rocha. Department of Computer Science Faculty of Sciences University of Porto

I/O OPERATIONS. UNIX Programming 2014 Fall by Euiseong Seo

I/O OPERATIONS. UNIX Programming 2014 Fall by Euiseong Seo

Contents. Programming Assignment 0 review & NOTICE. File IO & File IO exercise. What will be next project?

Memory Mapped I/O. Michael Jantz. Prasad Kulkarni. EECS 678 Memory Mapped I/O Lab 1

System-Level I/O. Topics Unix I/O Robust reading and writing Reading file metadata Sharing files I/O redirection Standard I/O

Contents. NOTICE & Programming Assignment #1. QnA about last exercise. File IO exercise

Hyo-bong Son Computer Systems Laboratory Sungkyunkwan University

System- Level I/O. Andrew Case. Slides adapted from Jinyang Li, Randy Bryant and Dave O Hallaron

All the scoring jobs will be done by script

Contents. NOTICE & Programming Assignment 0 review. What will be next project? File IO & File IO exercise

CS 201. Files and I/O. Gerson Robboy Portland State University

Content. Input Output Devices File access Function of File I/O Redirection Command-line arguments

Student Number: Instructor: Reid Section: L0101 (10:10-11:00am)

UNIX System Calls. Sys Calls versus Library Func

CSE 333 SECTION 3. POSIX I/O Functions

File IO and command line input CSE 2451

System-Level I/O Nov 14, 2002

[6 marks] All parts of this question assume the following C statement. Parts (b) through (e) assume a variable called ptrs.

Chapter 4 - Files and Directories. Information about files and directories Management of files and directories

PROGRAMMAZIONE I A.A. 2017/2018

A Typical Hardware System The course that gives CMU its Zip! System-Level I/O Nov 14, 2002

File Systems. q Files and directories q Sharing and protection q File & directory implementation

File Types in Unix. Regular files which include text files (formatted) and binary (unformatted)

CSC 271 Software I: Utilities and Internals

File System (FS) Highlights

Automated Test Generation in System-Level

File Access. FILE * fopen(const char *name, const char * mode);

17: Filesystem Examples: CD-ROM, MS-DOS, Unix

CSC209F Midterm (L0101) Fall 1999 University of Toronto Department of Computer Science

File Systems. Today. Next. Files and directories File & directory implementation Sharing and protection. File system management & examples

25.2 Opening and Closing a File

CS240: Programming in C

Design Choices 2 / 29

File Input and Output (I/O)

System-Level I/O March 31, 2005

Mode Meaning r Opens the file for reading. If the file doesn't exist, fopen() returns NULL.

Files and Directories Filesystems from a user s perspective

Student Number: Instructor: Reid Section: L5101 (6:10-7:00pm)

UNIT-V CONSOLE I/O. This section examines in detail the console I/O functions.

System Calls. Library Functions Vs. System Calls. Library Functions Vs. System Calls

CS240: Programming in C

CSC209 Fall Karen Reid 1

Naked C Lecture 6. File Operations and System Calls

2009 S2 COMP File Operations

Introduction to Computer Systems , fall th Lecture, Oct. 19 th

C-Refresher: Session 10 Disk IO

Input/Output and the Operating Systems

File (1A) Young Won Lim 11/25/16

CSCI-E28 Lecture 3 Outline. Directories, File Attributes, Bits, File Operations. Write our own versions of Unix programs

File I/O. Preprocessor Macros

INTRODUCTION TO UNIX FILE SYSTEM:

CSE 410: Systems Programming

UNIX System Programming

Lecture 7: Files. opening/closing files reading/writing strings reading/writing numbers (conversion to ASCII) command line arguments

CMPE-013/L. File I/O. File Processing. Gabriel Hugh Elkaim Winter File Processing. Files and Streams. Outline.

Standard File Pointers

System-Level I/O. William J. Taffe Plymouth State University. Using the Slides of Randall E. Bryant Carnegie Mellon University

Operating Systems. Processes

Student Number: Instructor: Reid Section: L0201 (12:10-1:00pm)

Linux Forensics. Newbug Tseng Oct

Slide Set 8. for ENCM 339 Fall 2017 Section 01. Steve Norman, PhD, PEng

Programming in C. Session 8. Seema Sirpal Delhi University Computer Centre

CSI 402 Lecture 2 Working with Files (Text and Binary)

Introduction to file management

Advanced Systems Security: Ordinary Operating Systems

void clearerr(file *stream); int feof(file *stream); int ferror(file *stream); int fileno(file *stream); #include <dirent.h>

The UNIX File System. File Systems and Directories UNIX inodes Accessing directories Understanding links in directories.

System- Level I/O. CS 485 Systems Programming Fall Instructor: James Griffioen

File Handling. Reference:

Quick review of previous lecture Ch6 Structure Ch7 I/O. EECS2031 Software Tools. C - Structures, Unions, Enums & Typedef (K&R Ch.

Thesis, antithesis, synthesis

Goals of this Lecture

File and Directories. Advanced Programming in the UNIX Environment

Fundamentals of Programming. Lecture 10 Hamed Rasifard

I/O Management! Goals of this Lecture!

I/O Management! Goals of this Lecture!

ECE 264 Exam 2. 6:30-7:30PM, March 9, You must sign here. Otherwise you will receive a 1-point penalty.

Master Calcul Scientifique - Mise à niveau en Informatique Written exam : 3 hours

Lab # 4. Files & Queues in C

Unix File and I/O. Outline. Storing Information. File Systems. (USP Chapters 4 and 5) Instructor: Dr. Tongping Liu

Memento: Time Travel for the Web

Systems Programming/ C and UNIX

Introduction. Files. 3. UNIX provides a simple and consistent interface to operating system services and to devices. Directories

UNIX input and output

Topic 8: I/O. Reading: Chapter 7 in Kernighan & Ritchie more details in Appendix B (optional) even more details in GNU C Library manual (optional)

CSE2301. Introduction. Streams and Files. File Access Random Numbers Testing and Debugging. In this part, we introduce

Introduction to Computer and Program Design. Lesson 6. File I/O. James C.C. Cheng Department of Computer Science National Chiao Tung University

Operating System Labs. Yuanbin Wu

Transcription:

Structs A collection of related data items struct record { char name[maxname]; int count; ; /* The semicolon is important! It terminates the declaration. */ struct record rec1; /*allocates space for the record */ strncpy(rec1.name, ".exe", MAXNAME); struct record *rec2 = malloc(sizeof(*rec2)); strncpy(rec2->name, ".gif", MAXNAME); 1

structs as arguments /* Remember: pass-by-value */ void print_record(struct record r) { printf("name = %s\n", r.name); printf("count=%d\n", r.count); print_record(rec1); print_record(*rec2); 2

Passing pointer or struct? /* Incorrect */ void incr_record(struct record r) { r.count++; /* Correct */ void incr_record(struct record *r) { r->count++; 3

Concrete Example int stat(const char *file_name, struct stat *buf); struct stat { dev_t st_dev; /* device */ ino_t st_ino; /* inode */ mode_t st_mode; /* protection */ nlink_t st_nlink; /* number of hard links */ uid_t st_uid; /* user ID of owner */ gid_t st_gid; /* group ID of owner */ dev_t st_rdev; /* device type (if inode device) */ off_t st_size; /* total size, in bytes */ blksize_t st_blksize; /* blocksize for filesystem I/O */ blkcnt_t st_blocks; /* number of blocks allocated */ time_t st_atime; /* time of last access */ time_t st_mtime; /* time of last modification */ time_t st_ctime; /* time of last change */ ; 4

stat By calling the stat function on a filename you want to fill in the fields of the struct stat. You must pass in a pointer, and there must be space allocated!!! struct stat sbuf; if(stat("myfile", &sbuf) == -1) { perror("stat"); exit(1); printf("owner = %d", sbuf.st_uid); 5

File Interfaces in Unix Unix has two main mechanisms for managing file access. file pointers: standard I/O library (Ch. 11) You deal with a pointer to a FILE structure that contains a file descriptor and a buffer. Use for regular files (more abstract and portable) file descriptors: low-level (Ch. 2) Each open file is identified by a small integer. Use for pipes, sockets. 6

stdin, stdout, stderr 3 files are automatically opened for any executing program: Standard input Standard output Standard error stdio name stdin stdout stderr File descriptor Reading from stdin by default comes from the keyboard Writing to stdout or stderr by default goes to the screen. 0 1 2 &K 7

Buffering un-buffered output appears immediately stderr is not buffered line buffered output appears when a full line has been written. stdout is line buffered when going to the screen block buffered output appears when a buffer is filled. normally output to a file is block buffered stdout is block buffered when redirected to a file. 8

File Operations Ch 2.3 For regular files use: fopen, fread, fwrite, fprintf, fgets, fscanf, fclose. FILE *fopen(const char *filename, const char *mode); char *fgets(char *s, int size, FILE *stream); reads the next line from a file pointer It reads at most size -1 characters Reading stops after a newline or EOF Appends a \0 character at the end of the string. Ch. 4.4 9

Files, Strings Problem: Given a name in the format Last, First, return a string in the format First Last char *reverse_name(char *src) { char *dest; char *sptr = strchr(src, ',');... return dest; We'll first do an example with pointers. 10

Using string functions char *reverse_name(char *src) { int src_len = strlen(src), dest_len = 0; char *dest; char *sptr = strchr(src, ','); /* allocate space for return string */ if ((dest = malloc(src_len+1)) == NULL) { return NULL; /* Move past the comma and the spaces between the comma and the first name */ sptr++; while(*sptr == ' ') sptr++; 11

/* Copy the first name to dest */ strncat(dest, sptr, strlen(src) + 1); /* Add a space to the destination string */ dest_len = strlen(dest); dest[dest_len] = ' '; dest[dest_len + 1] = '\0'; /* Copy the last name from src to dest */ strncat(dest, src, src_len - dest_len - 1); dest[src_len-1] = '\0'; return dest; Spot the errors 12

Calling reverse_name int main() { char *sptr, name[max]; Reading from standard input while((sptr = fgets(name, MAX, stdin))!= NULL) { /* strip the newline */ sptr = strchr(name, '\n'); *sptr = '\0'; printf("%s\n", reverse_name(name)); return 0; Spot the errors 13

Reading from a file? If we want to read from somewhere other than stdin, we need to open a file. How should we specify the filename? argv[0] == name of program argv[1] == first argument int main(int argc, char **argv) { if(argc!= 2) fprintf(stderr, "Usage: %s <filename>\n", argv[0]); exit(1); 14

stdio To open a file: FILE *fopen(const char *filename, const char *mode); filename identifies the file to open. mode tells how to open the file: "r" for reading, "w" for writing, "a" for appending returns a pointer to a FILE struct which is the handle to the file. This pointer will be used in subsequent operations. To close a file: void fclose(file *stream); 15

Example int main(int argc, char **argv) { char *sptr, name[max]; FILE *fp; if(argc!= 2) { fprintf(stderr, "Usage: do_reverse2 <file>\n"); exit(1); if((fp = fopen(argv[1], "r")) == NULL) { perror(argv[1]); exit(1); 16

Example (cont d) while((sptr = fgets(name, MAX, fp))!= NULL) { /* strip the newline */ sptr = strchr(name, '\n'); *sptr = '\0'; printf("%s\n", reverse_name(name)); return 0; 17

Error Handling Most system calls return -1 if an error occurs. (A few return NULL.) errno global variable that holds the numeric code of the last system call. Every process has errno assigned to zero at process creation time. When a system call error occurs, errno is set. A successful system call never affects the current value of errno. An unsuccessful system call always overwrites the current value of errno. Always check the return value of system calls! 18

perror() Library routine: void perror( char *str ) perror displays str, then a colon(:), then an English description of the last system call error as defined in errno.h. Protocol check system calls for a return value of -1 call perror() for an error description. 19

Binary I/O Recall that fgets reads characters. By contrast, fread and fwrite operate on bytes. size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream); read nmemb * size bytes into memory at ptr size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream); write nmemb * size bytes from ptr to the file pointer stream 20

Example It doesn t matter what the bytes contain! /* write an integer to the file */ int num = 21; n = fwrite(&num, sizeof(num), 1, fp); /* write a struct to the file */ struct rec { string name[20]; int num; r; r.num = 42; strncpy(r.name, "koala", 20); n = fwrite(&r, sizeof(r), 1, fp); 21

Example We need to know how to interpret the bytes from a file when reading. /* write an integer to the file */ int num; n = fread(&num, sizeof(num), 1, fp); /* write a struct to the file */ struct rec r; n = fread(&r, sizeof(r), 1, fp); /* display the contents of the variables */ printf("%d %s %d\n", num, r.name, r.num); 22

stat() int stat(const char *file_name, struct stat *buf); need to allocate memory for the stat struct before passing it to stat struct stat contains many fields including st_mode Useful macros: S_ISREG(modefield), S_ISDIR(modefield) 23

stat() struct stat sbuf; if(stat(pathname, &sbuf) == -1) { perror( stat ); if(s_isreg(sbuf.st_mode)) { printf( Regular file\n ); There are also defined variables for each of the permission sets. For example: if(sbuf.st_mode & S_IRUSR) { printf( Owner can read file\n ); 24

Directory Operations Recall that a directory is a special kind of file. We can read directory entries using similar functions. For directories use: DIR *opendir(const char *filename); struct dirent *readdir(dir *dirp); readdir works like fread on directory files. Each time readdir is called it returns a directory entry. Ch. 4.4 25

Example char *name, line[linesize], *lp; int len; DIR *dp; struct dirent *entry; FILE *fp; name = argv[1]; len = strlen(name); dp = opendir("."); What is wrong with this code? for (entry = readdir(dp); entry!= NULL; entry = readdir(dp)) if ((strncmp(name, entry->d_name, len)) == 0) { fp = fopen(entry->d_name, "r"); lp = fgets(line, LINESIZE, fp); fprintf(stdout, "%s: %s", entry->d_name, lp); closedir(dp); 26

Example char *name, line[linesize], *lp; int len; DIR *dp; struct dirent *entry; FILE *fp; name = argv[1]; len = strlen(name); dp = opendir("."); while loop equivalent to the for loop while( (entry = readdir(dp))!= NULL ) if ((strncmp(name, entry->d_name, len)) == 0) { fp = fopen(entry->d_name, "r"); lp = fgets(line, LINESIZE, fp); fprintf(stdout, "%s: %s", entry->d_name, lp); closedir(dp); 27