File I/O & UNIX System Interface

Slides:



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

January 13, Files – Chapter 2 Basic File Processing Operations.
CS1061 C Programming Lecture 17: Steams and Character I/O A. O’Riordan, 2004.
1 System Calls & Stdio. 2 Two processes open the same file Both keep writing to it What happens?
Kernel File Interface operating systems (or programming I/O in Unix)
1 System Calls, Stdio, and Course Wrap-Up COS 217 Professor Jennifer Rexford.
1 System Calls and Standard I/O Professor Jennifer Rexford
POSIX: Files Introduction to Operating Systems: Discussion 1 Read Solaris System Interface Guide: Ch. 5.1 Basic File I/O.
Chapter 17 - I/O in C. BYU CS/ECEn 124Input and Output2 Concepts to Learn… Standard Libraries Input/Output Data Streams printf() scanf() Variable Argument.
Adv. UNIX: lowIO/161 Advanced UNIX v Objectives –look at low-level operations for handling files Special Topics in Comp. Eng. 2 Semester.
Binary Search Tree For a node: The left subtree contains nodes with keys less than the node's key. The right subtree contains nodes with keys greater than.
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.
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.
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.
File IO and command line input CSE 2451 Rong Shi.
1 COMP 2130 Introduction to Computer Systems Computing Science Thompson Rivers University.
File I/O, Project 1: List ADT Bryce Boe 2013/07/02 CS24, Summer 2013 C.
Memory Layout, File I/O Bryce Boe 2013/06/27 CS24, Summer 2013 C.
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.
CNG 140 C Programming (Lecture set 10) Spring Chapter 10 Data Files.
C Programming Lecture 12 : File Processing
GAME203 – C Files stdio.h C standard Input/Output “getchar()”
Copyright ©: Nahrstedt, Angrave, Abdelzaher1 Tarek Abdelzaher Vikram Adve CS241 Systems Programming System Calls and I/O.
CS113 Introduction to C Instructor: Ioannis A. Vetsikas Lecture 11 : September 18.
File I/O open close lseek read and write – unbuffered I/O dup and dup2.
Adv. UNIX:fp/101 Advanced UNIX v Objectives of these slides: –a more detailed look at file processing in C Special Topics in Comp. Eng.
Files A collection of related data treated as a unit. Two types Text
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.
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.
Advanced Programming in the UNIX Environment Hop Lee.
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.
 Dynamic Memory Allocation  Linked Lists  void main() {{ ◦ FILE *file; ◦ char file_name[] = “file.txt”; ◦ if ((file = fopen(file_name, "w")) ==
By C. Shing ITEC Dept Radford University
Robust I/O package Chapter 11 practice problems
Chapter 9 – File Input Output
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
Session #5 File I/O Bit Masks, Fields & Bit Manipulations
Input / Output functions in C
CSC215 Lecture Input and Output.
Plan for the Day: I/O (beyond scanf and printf)
CS111 Computer Programming
CSE1320 Files in C Dr. Sajib Datta
CSE1320 Files in C Dr. Sajib Datta
C: Primer and Advanced Topics
Computer Science 210 Computer Organization
Input / Output functions in C
Files I/O, Streams, I/O Redirection, Reading with fscanf
Programming and Data Structures
File I/O We are used to reading from and writing to the terminal:
CSC215 Lecture Input and Output.
CSC215 Lecture Input and Output.
File Input and Output.
File I/O (1) Prof. Ikjun Yeom TA – Mugyo
I/O and Process Management
CSE 333 – Section 3 POSIX I/O Functions.
Lecture Starting K&R Chapter 7 and Appendix B
CSE 333 – Section 3 POSIX I/O Functions.
Line at a time I/O with fgets() and fputs()
Weeks 9-10 IO System Calls Standard IO (stdin, stdout) and Pipes
Module 12 Input and Output
Standard I/O Library Implementation
Low-Level I/O – the POSIX Layer CSE 333 Winter 2019
CS1100 Computational Engineering
CSc 352 File I/O Saumya Debray Dept. of Computer Science
I/O CS580U - Fall 2018.
File I/O We are used to reading from and writing to the terminal:
Presentation transcript:

File I/O & UNIX System Interface

File Open and Close File Pointer Open a file Close a file Pointer to FILE structure FILE *fp; FILE *fopen(char *name, char *mode); Open a file fp = fopen("filename","r"); "r" for read, "w" for write, "a" for append. Close a file fclose(fp);

FILE typedef struct { char *fpos; /* Current position of file pointer (absolute address) */ void *base; /* Pointer to the base of the file */ unsigned short handle; /* File handle or File descriptor*/ short flags; /* Flags (see FileFlags) */ short unget; /* 1-byte buffer for ungetc (b15=1 if non-empty) */ unsigned long alloc; /* Number of currently allocated bytes for the file */ unsigned short buffincrement; /* Number of bytes allocated at once */ } FILE;

Character File I/O Read a character from a file c=getc(fp);/* macro,EOF for end of file or error */ c=fgetc(fp);/* function */ int ungetc(int c, FILE *fp); /* push c back to fp */ Write a character to a file putc(c,fp); /* macro */ fputc(c,fp); /* function */ Check EOF or error feof(fp); /* non-zero if EOF */ ferror(fp); /* non-zero if error occurred on the stream fp */

EOF End Of File Symbolic Constant, making nothing in a program depend on the specific numeric value Defined in stdio.h #define EOF -1 or #define EOF 0

Example: Copy file1 file2 #include <stdio.h> int main(int argc, char *argv[]) { FILE *fp1, *fp2; int c; fp1 = fopen(argv[1],"r"); fp2 = fopen(argv[2],"w"); while((c=getc(fp1))!= EOF) putc(c,fp2); fclose(fp1); fclose(fp2); return 0; }

Formatted File I/O int fscanf(FILE *fp, char *format, ...) int fprintf(FILE *fp, char *format, ...)

Standard File I/O OS opens three files and provides (constant) file pointers to them (declared in stdio.h). OS assigns them to a program. stdin : standard input connected to the keyboard stdout : standard output connected to the screen stderr : standard error connected to the screen OS is responsible for closing the three files. You can close stdin and stdout if not needed. Reassigned by freopen. Macros defined in terms of stdin and stdout #define getchar() getc(stdin) #define putchar(c) putc((c), stdout)

Error Handling – stderr and exit /* filecopy: copy file ifp to file ofp */ void filecopy(FILE *ifp, FILE *ofp) { int c; while ((c = getc(ifp)) != EOF) putc(c, ofp); } #include <stdio.h> /* cat: concatenate files, version 2 */ main(int argc, char *argv[]) { FILE *fp; void filecopy(FILE *, FILE *); char *prog = argv[0]; /* program name for errors */ if (argc == 1 ) /* no args; copy standard input */ filecopy(stdin, stdout); else while (--argc > 0) if ((fp = fopen(*++argv, "r")) == NULL) { fprintf(stderr, "%s: can't open %s\n”, prog, *argv); exit(1); } else { filecopy(fp, stdout); fclose(fp); } if (ferror(stdout)) { fprintf(stderr, "%s: error writing stdout\n", prog); exit(2); exit(0);

Error Handling – stderr and exit exit calls fclose for each open output file to flush out any buffered output Return values 0: all is well Non-zero : abnormal situation

Line Input and Output char *fgets(char *line, int maxline, FILE *fp) /* fgets: get at most n chars from iop */ char *fgets(char *s, int n, FILE *iop) { register int c; register char *cs; cs = s; while (--n > 0 && (c = getc(iop)) != EOF) if ((*cs++ = c) == '\n’) break; *cs = '\0'; return (c == EOF && cs == s) ? NULL : s; }

Line Input and Output int *fputs(char *line, FILE *fp) /* fputs: put string s on file iop */ int fputs(char *s, FILE *iop) { int c; while (c = *s++) putc(c, iop); return ferror(iop) ? EOF : 0; }

Low Level I/O – System Calls int n_read = read(int fd, char *buf, int n); int n_written = write(int fd, char *buf, int n); fd: File Descriptor (File Handle) Non-negative integer to identify a file in an OS 0: standard input, 1: standard output, 2: standard error Each call returns a count of the number of bytes transferred.

System Call a request for a service that a program makes of an operating system’s kernel http://www.ibm.com/developerworks/library/l-linux-kernel/

Example: read(), write() #include "syscalls.h" main() /* copy input to output */ { char buf[BUFSIZ]; int n; while ((n = read(0, buf, BUFSIZ)) > 0) write(1, buf, n); return 0; } #include "syscalls.h" /* getchar: unbuffered single character input */ int getchar(void) { char c; return (read(0, &c, 1)==1) ? (unsigned char)c : EOF; }

Example: buffered read #include "syscalls.h” /* getchar: unbuffered simple buffered version */ int getchar(void) { static char buf[BUFSIZ] static char *bufp = buf; static int n = 0; if (n==0) { /* buffer is empty */ n = read(0, buf, sizeof buf); bufp = buf; } return (--n >= 0) ? (unsigned char) *buf++ : EOF;

Open, Creat, Close, Unlink #include <fcntl.h> int creat(char *name, int perms); int open(char *name, int flags, int perms); int fd; fd = creat(name, perms); fd = open(name, flags, perms); fd = open(name, O_RDONLY , 0); /* perms is always 0 for open */ O_RDONLY open for reading only O_WRONLY open for writing only O_RDWR open for both reading and writing

Open, Creat, Close, Unlink #include <stdio.h> #include <fcntl.h> #include "syscalls.h" #define PERMS 0666 /* RW for owner, group, others */ void error(char *, ...); /* cp: copy f1 to f2 */ main(int argc, char *argv[]) { int f1, f2, n; char buf[BUFSIZ]; if (argc != 3) error("Usage: cp from to"); if ((f1 = open(argv[1], O_RDONLY, 0)) == -1) error("cp: can't open %s", argv[1]); if ((f2 = creat(argv[2], PERMS)) == -1) error("cp: can't create %s, mode %03o”, argv[2], PERMS); while ((n = read(f1, buf, BUFSIZ)) > 0) if (write(f2, buf, n) != n) error("cp: write error on file %s", argv[2]); return 0; }

error() w/ variable argument list #include <stdio.h> #include <stdarg.h> /* error: print an error message and die */ void error(char *fmt, ...) { va_list args; va_start(args, fmt); /* Initializes args to retrieve the additional arguments after parameter fmt. */ /* variable argument list is replaced by a single argument (args) initialized by calling the va_start macro */ fprintf(stderr, "error: "); vprintf(stderr, fmt, args); fprintf(stderr, "\n"); va_end(args); exit(1); }

Random Access – Lseek Move around in a file without reading or writing any data long lseek(int fd, long offset, int origin) origin 0: offset measured from the beginning 1: offset measured from the current position 2: offset measured from the end of the file lseek(fd, 0L, 2); /* seek to the end of the file */ lseek(fd, 0L, 0); /* rewind to the beginning */

Random Access – Lseek #include "syscalls.h” int get(int fd, long pos, char *buf, int n) { if (lseek(fd, pos, 0) >= 0) /* get to pos */ return read(fd, buf, n); else return -1; }