Naked C Lecture 6. File Operations and System Calls
|
|
- Jordan McDowell
- 6 years ago
- Views:
Transcription
1 Naked C Lecture 6 File Operations and System Calls 20 August 2012
2 Libc and Linking Libc is the standard C library Provides most of the basic functionality that we've been using String functions, fork, printf Your code is automatically linked against libc by gcc You can link against other libraries using the -l option to gcc When using -l, specify the library name minus lib Example: linking against libtrace $ gcc -g -Wall -o tracesplit tracesplit.c -ltrace 2
3 Libc and System Calls Libc functions are provided for convenience Implement commonly used features in C It is possible to write your own versions of the libc functions How would you implement strlen(), for instance? Many tasks require the C library to invoke the kernel File I/O, memory allocation, networking, processes Kernel services can be invoked using system calls Wrapper functions in libc allow you to make system calls Wrappers have the same name as the system call 3
4 System Calls Application strlen malloc brk fopen Libc fork Syscall Wrappers open Kernel 4
5 File I/O in C We're going to look at two ways of doing file I/O in C File Handles, using libc functions File Descriptors, using syscall wrappers Both approaches have their place File handles are more convenient and easier to use You have encountered them already File descriptors are the only option for kernel-level programming Also file descriptors are used in other situations 5
6 File Handles FILE is a special type that describes a file in C The correct term is a file handle File handler functions in C either take or return a FILE * i.e. a pointer to a FILE structure The contents of the FILE structure are unimportant The FILE structure is opaque you will never touch it directly 6
7 File I/O The basics of file I/O in C Step 1 #include <stdio.h> Step 2 use fopen to open the file and get a FILE * Step 3 perform your I/O using functions like fgets, fprintf etc. Step 4 close your file using fclose Don't forget to check for errors as you go! 7
8 Binary Files Text files Human-readable but can be wasteful in terms of storage e.g is an int but requires 8 bytes to store Binary files Store data in the same format as it is in memory e.g. an int is always four bytes in a binary file Can be more compact Faster for your program to read no need to convert strings Write entire data structures to disk Just be careful with padding, use packed structs 8
9 Built-in File Pointers There are 3 file handles that are automatically opened stdin Input from the console stdout Output to the console stderr Error output to the console We used stdin back in Lecture 3 when using fgets #include <stdio.h> char input[256]; while (fgets(input, sizeof(input), stdin)!= NULL) { /* Note the lack of '\n' the string returned * by fgets() still has the newline on the end */ printf( You just typed: %s, input); } 9
10 Standard Error Normally stderr goes to the console just like stdout However, the streams can be redirected to separate files Use stdout for regular console output Use stderr for error messages and debug output 10
11 End of File EOF is a special value that indicates the end of a file Often returned by file handle functions in C In the GNU standard C library, EOF is equal to -1 11
12 Opening a file fopen opens a given file Takes 2 parameters: char *path and char *mode path is a string containing the path to the file to be opened mode is a string describing how the file should be opened fopen returns a FILE * for the file that was just opened Returns NULL if an error occurred 12
13 Opening a File Supported modes for fopen r open the file for reading r+ open the file for reading and writing w create a new file for writing Any existing file is overwritten w+ create a new file for reading and writing Any existing file is overwritten a open the file for appending All writes appear at the end of the file, if it previously existed a+ open the file for reading and appending All writes appear at the end of the file All reads begin from the start of the file 13
14 Error Handling perror prints the system error message Takes 1 argument: a string to prepend to the error message Writes a message to stdout that describes the most recent error Useful for explaining why a standard library function failed errno variable that stores the current error status #include <errno.h> to get access to errno errno is used by perror to print an appropriate message You may want different behaviour for specific errors To do this, you can switch based on errno 14
15 Error Handling Common values for errno have well-defined names EAGAIN resource unavailable, try again later EINTR function call interrupted by signal EBADF bad file descriptor EADDRINUSE address already in use EACCES permission denied ECONNREFUSED connection refused EINVAL invalid argument 15
16 File Opening Example Trying to open a file for writing Note the use of perror when checking for errors #include <stdio.h> FILE *f; f = fopen( /tmp/test, w ); if (f == NULL) { perror( example fopen ); } 16
17 Checking File State feof check if an EOF was encountered Takes one parameter: the FILE * to be checked Returns true if the EOF flag is set for that file ferror check if an error occurred Takes one parameter: the FILE * to be checked Returns true if the error flag is set for that file 17
18 Closing a File fclose closes the file associated with a FILE * Output is flushed before closing Do not try to reuse the file pointer after calling fclose on it Returns 0 on success and EOF on failure 18
19 Reading and Writing character string formatted binary read fgetc() fgets() fscanf() fread() write fputc() fputs() fprintf() fwrite() 19
20 Reading from a File fgetc read a single character from a file Takes one parameter: the FILE * to read from Returns an int (!) containing the character read Every character has a numeric value (ASCII value) For example, 'A' is equal to 65 'man ascii' will give you a full ASCII table The returned int is just the ASCII value of the character Returns EOF on end of file or error 20
21 Reading from a File Using fgetc to count B's Maybe not the best way to do this, but it's just an example :) int count_b(char *filename) { int c, count; FILE *f = fopen(filename, r ); if (!f) return 0; while ((c = fgetc(f))!= EOF) { if (c == 'b' c == 'B') { count ++; } } fclose(f); return count; } 21
22 Reading from a File fgets read a line from a file We've already seen fgets when learning about reading from stdin Three parameters: char *s, int size, FILE *stream s is the buffer to read the line into size is the size of the buffer stream is the file to read from Remember, the newline character is stored in the buffer 22
23 Reading from a File fscanf read formatted input from a file Just like scanf, except reading from a FILE * instead of stdin Same formatting rules apply Remember, you need to pass in pointers for your variables Returns the number of items successfully assigned to variables int tstamp, val, ret; char name[128]; FILE *fp = fopen( input.txt, r ); ret = fscanf(fp, %d %128s %d\n, &tstamp, name, &val); if (ret!= 3) { /* Should report error if ret is not EOF */ fclose(fp); return; } 23
24 Reading from a File fread read binary data from a file Takes four parameters: void *ptr, size_t size, size_t nmemb and FILE *stream stream is the file you wish to read from ptr points to the start of the memory to read into size describes the size of each data element nmemb describes the number of elements to read Returns the number of elements successfully read This will be zero in the event of both EOF and error Use feof and ferror to find out what happened 24
25 Reading from a File fread example Reading a series of doubles from a file double nums[100]; FILE *fp; int numread = 0; fp = fopen( doubles.bin, r ); if (fp) { numread = fread(nums, sizeof(double), 100, fp); if (numread!= 100) { if (ferror(fp)) { perror( fread ); } } } 25
26 Writing to a File fputc write a single character to a file Takes two parameters: int c and FILE *stream stream is obviously the file to write the character to c is the character to be written, expressed as an int (again) Returns an int representing the character written Unless there is an error, in which case it returns EOF int ch; FILE *f = fopen( /tmp/test, w ); for (ch = 'A'; ch <= 'Z'; ch++) { if (fputc(ch, f) == EOF) { perror( fputc ); break; } } fclose(f); 26
27 Writing to a File fputs write a string to a file Does NOT stop at a newline, only at '\0' Does NOT automatically put a newline at the end of the output Returns EOF on error, non-negative number on success char str[100]; /* I'm naughty and don't check for errors */ FILE *f = fopen( /tmp/test, w ); while(fgets(str, sizeof(str), stdin)!= NULL) { if (fputs(str, f) < 0) { perror( fputs ); break; } } fclose(f); 27
28 Writing to a File fprintf print a formatted string to a file Almost exactly the same as printf same formatting rules The first argument is a FILE * describing where the output should be written Returns the number of characters written successfully int foo = 100; char *str = Test ; /* I'm naughty and don't check for errors */ FILE *f = fopen( /tmp/test, w ); fprintf(f, fprintf is easy! %s %d\n, str, foo); fclose(f); /* fprintf is great for writing error/debug output */ fprintf(stderr, This is going to stderr ); 28
29 Writing to a File fwrite write binary data to a file Takes four parameters: void *ptr, size_t size, size_t nmemb and FILE *stream stream is the file you wish to write to ptr points to the start of the data you wish to write size describes the size of each data element nmemb describes the number of elements to write Returns the number of elements successfully written fwrite is ideal for writing buffer contents to a file Note the void pointer as a parameter! 29
30 Writing to a File Using fwrite to write a large buffer to a file In this example, I'm writing out an array of ints FILE *fp = NULL; int nums[1024]; size_t written; // pretend this is filled in fp = fopen( random.numbers, w ); written = fwrite(nums, sizeof(int), 1024, fp); if (written!= 1024) { perror( fwrite ); } fclose(fp); return(written == 1024); 30
31 Flushing a File Standard I/O is line buffered Output is not written to disk or the terminal immediately Wait for a newline, the buffer to fill or the file to be closed Saves the OS having to touch disk for every I/O function On occasion, you may wish to force all buffered output to be written fflush flush all buffered I/O immediately Takes one parameter the FILE * to be flushed fclose automatically flushes the stream before closing fputs( This string has no newline, stdout); /* The string won't be printed until I flush stdout */ fflush(stdout); 31
32 File I/O with System Calls A system call is a request to the kernel to do something File I/O is controlled by the kernel, so requires system calls File handle functions invoke the system calls for us System calls are expensive! OS must save state, take control, perform action, return control Be careful about making needless system calls Everything in Unix (and derivatives) is a file Understanding file I/O at the system level is rather important System call API for files also covers devices / hardware, pipes Lots of crossover with sockets too (networking) 32
33 File Descriptors First, we need to know about file descriptors A file descriptor (or fd) is an abstract representation of a file An fd can also represent sockets, pipes, directories and more! In POSIX, a file descriptor is an int and each fd is stored in a table Each process has its own fd table 0, 1 and 2 are fds for stdin, stdout and stderr, respectively The fd is an index used to find the data structure describing the open file in the kernel File offset the location where the next read or write operation will occur File status and access flags e.g. read only, non-blocking, append mode 33
34 Opening a File Descriptor open creates a new open file descriptor Two parameters: char *path and int flags path is the file to open flags describe how the file should be opened flags should be specified by bitwise ORing One of the flags must be either: O_RDONLY (read only) O_WRONLY (write only) O_RDWR (read and write) Returns the new file descriptor or -1 if an error occurred Use perror to find out what happened 34
35 Opening a File Descriptor Some other file descriptor flags O_CREAT: create the file if it doesn't already exist O_EXCL: ensure no file already exists with this name O_CREAT must also be set to use this This will prevent you from overwriting an existing file O_APPEND: enable append mode for the file If file exists, do not overwrite. Instead, append to the end of it O_NONBLOCK: enable non-blocking mode Read operations may return immediately if no data available Will set errno to EAGAIN O_NOATIME: read operations will not update the access time Useful for backup operations 35
36 Closing a File Descriptor close closes a file descriptor Takes one parameter: the fd to be closed Returns 0 on success, -1 if an error occurs 36
37 Opening a File Descriptor open and close example Open a file for appending but create it if it doesn't exit #include #include #include #include <sys/types.h> <sys/stat.h> <fcntl.h> <stdio.h> // // // // for for for for open open open perror int fd; fd = open( myfile.txt, O_WRONLY O_CREAT O_APPEND); if (fd == -1) { perror( open ); return -1; } close(fd); 37
38 Reading from a File Descriptor read reads a given number of bytes from a fd Three parameters: int fd, void *buf, size_t count fd is the file descriptor to read from buf is a pointer to memory that data will be read into count is the number of bytes to read Returns the number of bytes read Returns -1 if an error occurs Returns 0 if the end of file is reached (not EOF) It is possible for read to return less bytes than you asked for e.g. if your read is interrupted by a signal 38
39 Reading from a File Descriptor Reading up to 100 bytes from myfile.txt #include <unistd.h> int fd, buf_read; char buf[100]; // for read fd = open( myfile.txt, O_RDONLY); if (fd == -1) { perror( open ); return -1; } buf_read = read(fd, buf, 100); if (buf_read < 0) { perror( read ); return -1; } close(fd); 39
40 Writing to a File Descriptor write write contents of memory to a file descriptor Three params: int fd, void *buf and size_t count These have the same meaning as read, except this will copy from memory to the file descriptor rather than the other way around. Returns the number of bytes written Returns -1 on error Again, write may return less than count It is up to you to ensure any subsequent writes begin from the right place! 40
41 Writing to a File Descriptor Using write to display a string on the terminal char str[] = STOP, COLLABORATE AND LISTEN!\n int written = 0, ret; char *ptr = str; int len = strlen(str); while (written < len) { ret = write(1, ptr, len written); if (ret < 0) { perror( write ); break; } written += ret; ptr += ret; } 41
42 Changing File Offset lseek repositions the file offset for a file descriptor Takes 3 parameters: int fd, off_t newoff, int whence fd is the file descriptor to reposition newoff quantifies the change to be made off_t is another special type used for file offsets whence describes how to adjust the file offset SEEK_SET: directly set the offset to newoff SEEK_CUR: increment the offset by newoff SEEK_END: set the offset to newoff bytes past the file end Returns the new file offset if an error occurs, returns -1 42
43 More File Descriptor System Calls fsync flushes a file descriptor Works just like fflush, except it takes an fd instead of a FILE * Returns 0 on success, -1 on error dup duplicates a file descriptor Takes the file descriptor to copy as a parameter Returns the next available file descriptor Both descriptors now refer to the same file The duplicate has the same file offset, modes etc. If the file offset is changed in one fd, it is also changed in the other 43
44 Descriptors to Handles and Back Again fdopen upgrade a file descriptor to a file handle Works exactly like fopen, except takes a fd instead of a filename The mode parameter must be compatible with the mode of the fd Do NOT call close on the file descriptor after doing this! fileno get the file descriptor for a file handle Takes one parameter: a FILE * Returns the file descriptor associated with that file Returns -1 if the file handle is bad 44
45 File Handles vs File Descriptors File handles operate at a higher level to file descriptors A FILE * will contain a file descriptor File handles offer more options when reading/writing Writing to a file handle: fwrite, fputs, fputc, fprintf Writing to a file descriptor: write File handle code only works on files File descriptor code can be easily adapted to sockets, pipes etc. File handle functions are not available in the kernel You have to use the lower-level system calls then! 45
46 File Handles vs File Descriptors Use file handles in userspace applications Unless you want a file, socket, pipe, etc. to be interchangeable Use file descriptors when working in or near the kernel Kernel modules and device drivers Whatever you do, don't mix and match for the same file! e.g. don't call both read and fread on the same file 46
47 More System Calls Heap memory allocation using brk and sbrk brk and sbrk increase the size of the program's heap These system calls are invoked when you call malloc malloc optimises the process Userspace programs should never call brk or sbrk directly 47
48 More System Calls Socket programming Networking: connections, sending and receiving messages Uses file descriptors but slightly more complicated Will cover in more detail in a future lecture Unlike file I/O, there is no nice socket handle API 48
49 More System Calls Processes We've already encountered many of the libc wrappers fork, waitpid, execve, exit All of the various exec* functions that we saw invoke execve Each took slightly different input and then converted it into parameters suitable for calling execve 49
50 More System Calls File system operations chdir changes the current working directory getcwd gets the current working directory chown changes the owner of a file mkdir will create a directory rename will change the name or location of a file There are many, many more... Most standard Unix tools are really easy to implement! There's a matching syscall wrapper function for most of them They even usually have the same name! 50
51 strace strace see what system calls your program is using strace is run on the command line, just like gdb Prints each system call, its arguments and the return value You can attach strace to a running process Allows you to see what a hung process is doing Running a program with strace -f tells strace to follow all forks $ strace -f./myprog Attaching strace to an existing process In this example, the process has the pid 3443 $ strace -f --pid=
52 Recap System Calls Operations that require the kernel are done via system calls Userspace programs do not invoke system calls directly libc implements wrapper functions for system calls Not all libc functions are wrappers Some require no system calls at all Others may call syscall wrappers 52
53 Recap File I/O using file handles Abstraction of system calls that can be used for file operations only Most userspace programs should use file handles File handles use a special structure: a FILE * Many options for reading and writing to files fprintf, fgets, fscanf, fputs, fputc, fgetc, fread, fwrite Not usable at the kernel level 53
54 Recap File I/O using file descriptors Using the system call wrappers directly Uses a file descriptor, which is just an integer representing a file File descriptors also represent sockets, pipes and directories No nice API functions for formatting input or output Only read and write available Will need to be familiar with fd operations to do I/O in kernel space 54
CS240: Programming in C
CS240: Programming in C Lecture 13 si 14: Unix interface for working with files. Cristina Nita-Rotaru Lecture 13/Fall 2013 1 Working with Files (I/O) File system: specifies how the information is organized
More informationCSE 410: Systems Programming
CSE 410: Systems Programming Input and Output Ethan Blanton Department of Computer Science and Engineering University at Buffalo I/O Kernel Services We have seen some text I/O using the C Standard Library.
More informationCS240: Programming in C
CS240: Programming in C Lecture 15: Unix interface: low-level interface Cristina Nita-Rotaru Lecture 15/Fall 2013 1 Streams Recap Higher-level interface, layered on top of the primitive file descriptor
More informationCSE 333 SECTION 3. POSIX I/O Functions
CSE 333 SECTION 3 POSIX I/O Functions Administrivia Questions (?) HW1 Due Tonight Exercise 7 due Monday (out later today) POSIX Portable Operating System Interface Family of standards specified by the
More informationUNIX System Programming
File I/O 경희대학교컴퓨터공학과 조진성 UNIX System Programming File in UNIX n Unified interface for all I/Os in UNIX ü Regular(normal) files in file system ü Special files for devices terminal, keyboard, mouse, tape,
More informationSystems Programming. 08. Standard I/O Library. Alexander Holupirek
Systems Programming 08. Standard I/O Library Alexander Holupirek Database and Information Systems Group Department of Computer & Information Science University of Konstanz Summer Term 2008 Last lecture:
More informationSystems Programming. COSC Software Tools. Systems Programming. High-Level vs. Low-Level. High-Level vs. Low-Level.
Systems Programming COSC 2031 - Software Tools Systems Programming (K+R Ch. 7, G+A Ch. 12) The interfaces we use to work with the operating system In this case: Unix Programming at a lower-level Systems
More informationWhat Is Operating System? Operating Systems, System Calls, and Buffered I/O. Academic Computers in 1983 and Operating System
What Is Operating System? Operating Systems, System Calls, and Buffered I/O emacs gcc Browser DVD Player Operating System CS 217 1 Abstraction of hardware Virtualization Protection and security 2 Academic
More informationSystem Software Experiment 1 Lecture 7
System Software Experiment 1 Lecture 7 spring 2018 Jinkyu Jeong ( jinkyu@skku.edu) Computer Systems Laboratory Sungyunkwan University http://csl.skku.edu SSE3032: System Software Experiment 1, Spring 2018
More informationMode Meaning r Opens the file for reading. If the file doesn't exist, fopen() returns NULL.
Files Files enable permanent storage of information C performs all input and output, including disk files, by means of streams Stream oriented data files are divided into two categories Formatted data
More informationOperating System Labs. Yuanbin Wu
Operating System Labs Yuanbin Wu cs@ecnu Annoucement Next Monday (28 Sept): We will have a lecture @ 4-302, 15:00-16:30 DON'T GO TO THE LABORATORY BUILDING! TA email update: ecnucchuang@163.com ecnucchuang@126.com
More informationCSE 333 SECTION 3. POSIX I/O Functions
CSE 333 SECTION 3 POSIX I/O Functions Administrivia Questions (?) HW1 Due Tonight HW2 Due Thursday, July 19 th Midterm on Monday, July 23 th 10:50-11:50 in TBD (And regular exercises in between) POSIX
More informationPhysical Files and Logical Files. Opening Files. Chap 2. Fundamental File Processing Operations. File Structures. Physical file.
File Structures Physical Files and Logical Files Chap 2. Fundamental File Processing Operations Things you have to learn Physical files and logical files File processing operations: create, open, close,
More informationContent. Input Output Devices File access Function of File I/O Redirection Command-line arguments
File I/O Content Input Output Devices File access Function of File I/O Redirection Command-line arguments UNIX and C language C is a general-purpose, high-level language that was originally developed by
More informationSection 3: File I/O, JSON, Generics. Meghan Cowan
Section 3: File I/O, JSON, Generics Meghan Cowan POSIX Family of standards specified by the IEEE Maintains compatibility across variants of Unix-like OS Defines API and standards for basic I/O: file, terminal
More informationFiles and Streams Opening and Closing a File Reading/Writing Text Reading/Writing Raw Data Random Access Files. C File Processing CS 2060
CS 2060 Files and Streams Files are used for long-term storage of data (on a hard drive rather than in memory). Files and Streams Files are used for long-term storage of data (on a hard drive rather than
More informationCSci 4061 Introduction to Operating Systems. Input/Output: High-level
CSci 4061 Introduction to Operating Systems Input/Output: High-level I/O Topics First, cover high-level I/O Next, talk about low-level device I/O I/O not part of the C language! High-level I/O Hide device
More informationImportant Dates. October 27 th Homework 2 Due. October 29 th Midterm
CSE333 SECTION 5 Important Dates October 27 th Homework 2 Due October 29 th Midterm String API vs. Byte API Recall: Strings are character arrays terminated by \0 The String API (functions that start with
More informationLecture 3. Introduction to Unix Systems Programming: Unix File I/O System Calls
Lecture 3 Introduction to Unix Systems Programming: Unix File I/O System Calls 1 Unix File I/O 2 Unix System Calls System calls are low level functions the operating system makes available to applications
More informationPROGRAMMAZIONE I A.A. 2017/2018
PROGRAMMAZIONE I A.A. 2017/2018 INPUT/OUTPUT INPUT AND OUTPUT Programs must be able to write data to files or to physical output devices such as displays or printers, and to read in data from files or
More informationOutline. OS Interface to Devices. System Input/Output. CSCI 4061 Introduction to Operating Systems. System I/O and Files. Instructor: Abhishek Chandra
Outline CSCI 6 Introduction to Operating Systems System I/O and Files File I/O operations File Descriptors and redirection Pipes and FIFOs Instructor: Abhishek Chandra 2 System Input/Output Hardware devices:
More informationCSC209H Lecture 3. Dan Zingaro. January 21, 2015
CSC209H Lecture 3 Dan Zingaro January 21, 2015 Streams (King 22.1) Stream: source of input or destination for output We access a stream through a file pointer (FILE *) Three streams are available without
More informationAll the scoring jobs will be done by script
File I/O Prof. Jinkyu Jeong( jinkyu@skku.edu) TA-Seokha Shin(seokha.shin@csl.skku.edu) TA-Jinhong Kim( jinhong.kim@csl.skku.edu) Computer Systems Laboratory Sungkyunkwan University http://csl.skku.edu
More informationCSC 271 Software I: Utilities and Internals
CSC 271 Software I: Utilities and Internals Lecture 13 : An Introduction to File I/O in Linux File Descriptors All system calls for I/O operations refer to open files using a file descriptor (a nonnegative
More informationGoals of this Lecture
I/O Management 1 Goals of this Lecture Help you to learn about: The Unix stream concept Standard C I/O functions Unix system-level functions for I/O How the standard C I/O functions use the Unix system-level
More informationProcess Management! Goals of this Lecture!
Process Management! 1 Goals of this Lecture! Help you learn about:" Creating new processes" Programmatically redirecting stdin, stdout, and stderr" Unix system-level functions for I/O" The Unix stream
More informationI/O Management! Goals of this Lecture!
I/O Management! 1 Goals of this Lecture! Help you to learn about:" The Unix stream concept" Standard C I/O functions" Unix system-level functions for I/O" How the standard C I/O functions use the Unix
More informationI/O Management! Goals of this Lecture!
I/O Management! 1 Goals of this Lecture! Help you to learn about:" The Unix stream concept" Standard C I/O functions" Unix system-level functions for I/O" How the standard C I/O functions use the Unix
More informationStandard File Pointers
1 Programming in C Standard File Pointers Assigned to console unless redirected Standard input = stdin Used by scan function Can be redirected: cmd < input-file Standard output = stdout Used by printf
More informationCS246 Spring14 Programming Paradigm Files, Pipes and Redirection
1 Files 1.1 File functions Opening Files : The function fopen opens a file and returns a FILE pointer. FILE *fopen( const char * filename, const char * mode ); The allowed modes for fopen are as follows
More informationCMPSC 311- Introduction to Systems Programming Module: Input/Output
CMPSC 311- Introduction to Systems Programming Module: Input/Output Professor Patrick McDaniel Fall 2014 Input/Out Input/output is the process of moving bytes into and out of the process space. terminal/keyboard
More informationIntroduction to file management
1 Introduction to file management Some application require input to be taken from a file and output is required to be stored in a file. The C language provides the facility of file input-output operations.
More informationFile Access. FILE * fopen(const char *name, const char * mode);
File Access, K&R 7.5 Dealing with named files is surprisingly similar to dealing with stdin and stdout. Start by declaring a "file pointer": FILE *fp; /* See Appendix B1.1, pg. 242 */ header
More informationRicardo Rocha. Department of Computer Science Faculty of Sciences University of Porto
Ricardo Rocha Department of Computer Science Faculty of Sciences University of Porto For more information please consult Advanced Programming in the UNIX Environment, 3rd Edition, W. Richard Stevens and
More informationstructs as arguments
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
More informationUNIX System Calls. Sys Calls versus Library Func
UNIX System Calls Entry points to the kernel Provide services to the processes One feature that cannot be changed Definitions are in C For most system calls a function with the same name exists in the
More informationIntroduction to Programming in C Department of Computer Science and Engineering. Lecture No. #47. File Handling
Introduction to Programming in C Department of Computer Science and Engineering Lecture No. #47 File Handling In this video, we will look at a few basic things about file handling in C. This is a vast
More informationCSE2301. Introduction. Streams and Files. File Access Random Numbers Testing and Debugging. In this part, we introduce
Warning: These notes are not complete, it is a Skelton that will be modified/add-to in the class. If you want to us them for studying, either attend the class or get the completed notes from someone who
More informationTopic 8: I/O. Reading: Chapter 7 in Kernighan & Ritchie more details in Appendix B (optional) even more details in GNU C Library manual (optional)
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) No C language primitives for I/O; all done via function
More informationFile I/O. Preprocessor Macros
Computer Programming File I/O. Preprocessor Macros Marius Minea marius@cs.upt.ro 4 December 2017 Files and streams A file is a data resource on persistent storage (e.g. disk). File contents are typically
More information2009 S2 COMP File Operations
2009 S2 COMP1921 9. File Operations Oliver Diessel odiessel@cse.unsw.edu.au Last updated: 16:00 22 Sep 2009 9. File Operations Topics to be covered: Streams Text file operations Binary file operations
More informationUNIT IV-2. The I/O library functions can be classified into two broad categories:
UNIT IV-2 6.0 INTRODUCTION Reading, processing and writing of data are the three essential functions of a computer program. Most programs take some data as input and display the processed data, often known
More informationLecture 9: File Processing. Quazi Rahman
60-141 Lecture 9: File Processing Quazi Rahman 1 Outlines Files Data Hierarchy File Operations Types of File Accessing Files 2 FILES Storage of data in variables, arrays or in any other data structures,
More informationThe course that gives CMU its Zip! I/O Nov 15, 2001
15-213 The course that gives CMU its Zip! I/O Nov 15, 2001 Topics Files Unix I/O Standard I/O A typical hardware system CPU chip register file ALU system bus memory bus bus interface I/O bridge main memory
More informationAccessing Files in C. Professor Hugh C. Lauer CS-2303, System Programming Concepts
Accessing Files in C Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie, Absolute C++, by Walter
More informationIntermediate Programming, Spring 2017*
600.120 Intermediate Programming, Spring 2017* Misha Kazhdan *Much of the code in these examples is not commented because it would otherwise not fit on the slides. This is bad coding practice in general
More informationLecture 23: System-Level I/O
CSCI-UA.0201-001/2 Computer Systems Organization Lecture 23: System-Level I/O Mohamed Zahran (aka Z) mzahran@cs.nyu.edu http://www.mzahran.com Some slides adapted (and slightly modified) from: Clark Barrett
More informationAll the scoring jobs will be done by script
File I/O Prof. Jin-Soo Kim( jinsookim@skku.edu) TA Sanghoon Han(sanghoon.han@csl.skku.edu) Computer Systems Laboratory Sungkyunkwan University http://csl.skku.edu Announcement (1) All the scoring jobs
More informationfopen() fclose() fgetc() fputc() fread() fwrite()
The ability to read data from and write data to files is the primary means of storing persistent data, data that does not disappear when your program stops running. The abstraction of files that C provides
More informationI/O OPERATIONS. UNIX Programming 2014 Fall by Euiseong Seo
I/O OPERATIONS UNIX Programming 2014 Fall by Euiseong Seo Files Files that contain a stream of bytes are called regular files Regular files can be any of followings ASCII text Data Executable code Shell
More informationFile I/O. Arash Rafiey. November 7, 2017
November 7, 2017 Files File is a place on disk where a group of related data is stored. Files File is a place on disk where a group of related data is stored. C provides various functions to handle files
More informationOperating systems. Lecture 7
Operating systems. Lecture 7 Michał Goliński 2018-11-13 Introduction Recall Plan for today History of C/C++ Compiler on the command line Automating builds with make CPU protection rings system calls pointers
More informationQuick review of previous lecture Ch6 Structure Ch7 I/O. EECS2031 Software Tools. C - Structures, Unions, Enums & Typedef (K&R Ch.
1 Quick review of previous lecture Ch6 Structure Ch7 I/O EECS2031 Software Tools C - Structures, Unions, Enums & Typedef (K&R Ch.6) Structures Basics: Declaration and assignment Structures and functions
More informationLecture files in /home/hwang/cs375/lecture05 on csserver.
Lecture 5 Lecture files in /home/hwang/cs375/lecture05 on csserver. cp -r /home/hwang/cs375/lecture05. scp -r user@csserver.evansville.edu:/home/hwang/cs375/lecture05. Project 1 posted, due next Thursday
More informationUnix File and I/O. Outline. Storing Information. File Systems. (USP Chapters 4 and 5) Instructor: Dr. Tongping Liu
Outline Unix File and I/O (USP Chapters 4 and 5) Instructor: Dr. Tongping Liu Basics of File Systems Directory and Unix File System: inode UNIX I/O System Calls: open, close, read, write, ioctl File Representations:
More information25.2 Opening and Closing a File
Lecture 32 p.1 Faculty of Computer Science, Dalhousie University CSCI 2132 Software Development Lecture 32: Dynamically Allocated Arrays 26-Nov-2018 Location: Chemistry 125 Time: 12:35 13:25 Instructor:
More informationFiles. Eric McCreath
Files Eric McCreath 2 What is a file? Information used by a computer system may be stored on a variety of storage mediums (magnetic disks, magnetic tapes, optical disks, flash disks etc). However, as a
More informationC Basics And Concepts Input And Output
C Basics And Concepts Input And Output Report Working group scientific computing Department of informatics Faculty of mathematics, informatics and natural sciences University of Hamburg Written by: Marcus
More informationFile and Console I/O. CS449 Spring 2016
File and Console I/O CS449 Spring 2016 What is a Unix(or Linux) File? File: a resource for storing information [sic] based on some kind of durable storage (Wikipedia) Wider sense: In Unix, everything is
More informationInput / Output Functions
CSE 2421: Systems I Low-Level Programming and Computer Organization Input / Output Functions Presentation G Read/Study: Reek Chapter 15 Gojko Babić 10-03-2018 Input and Output Functions The stdio.h contain
More informationI/O OPERATIONS. UNIX Programming 2014 Fall by Euiseong Seo
I/O OPERATIONS UNIX Programming 2014 Fall by Euiseong Seo Files Files that contain a stream of bytes are called regular files Regular files can be any of followings ASCII text Data Executable code Shell
More informationEM108 Software Development for Engineers
EE108 Section 4 Files page 1 of 14 EM108 Software Development for Engineers Section 4 - Files 1) Introduction 2) Operations with Files 3) Opening Files 4) Input/Output Operations 5) Other Operations 6)
More informationStandard C Library Functions
Demo lecture slides Although I will not usually give slides for demo lectures, the first two demo lectures involve practice with things which you should really know from G51PRG Since I covered much of
More informationStandard I/O in C, Computer System and programming in C
Standard I/O in C, Contents 1. Preface/Introduction 2. Standardization and Implementation 3. File I/O 4. Standard I/O Library 5. Files and Directories 6. System Data Files and Information 7. Environment
More informationOperating System Labs. Yuanbin Wu
Operating System Labs Yuanbin Wu cs@ecnu Announcement Project 1 due 21:00, Oct. 8 Operating System Labs Introduction of I/O operations Project 1 Sorting Operating System Labs Manipulate I/O System call
More informationFile System User API
File System User API Blunk Microsystems file system API includes the file-related routines from Standard C and POSIX, as well as a number of non-standard functions that either meet a need unique to embedded
More informationFile (1A) Young Won Lim 11/25/16
File (1A) Copyright (c) 2010-2016 Young W. Lim. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version
More informationFile I/O. Jin-Soo Kim Computer Systems Laboratory Sungkyunkwan University
File I/O Jin-Soo Kim (jinsookim@skku.edu) Computer Systems Laboratory Sungkyunkwan University http://csl.skku.edu Unix Files A Unix file is a sequence of m bytes: B 0, B 1,..., B k,..., B m-1 All I/O devices
More informationData File and File Handling
Types of Disk Files Data File and File Handling Text streams are associated with text-mode files. Text-mode files consist of a sequence of lines. Each line contains zero or more characters and ends with
More informationFall 2017 :: CSE 306. File Systems Basics. Nima Honarmand
File Systems Basics Nima Honarmand File and inode File: user-level abstraction of storage (and other) devices Sequence of bytes inode: internal OS data structure representing a file inode stands for index
More informationCSI 402 Lecture 2 Working with Files (Text and Binary)
CSI 402 Lecture 2 Working with Files (Text and Binary) 1 / 30 AQuickReviewofStandardI/O Recall that #include allows use of printf and scanf functions Example: int i; scanf("%d", &i); printf("value
More informationHow do we define pointers? Memory allocation. Syntax. Notes. Pointers to variables. Pointers to structures. Pointers to functions. Notes.
, 1 / 33, Summer 2010 Department of Computer Science and Engineering York University Toronto June 15, 2010 Table of contents, 2 / 33 1 2 3 Exam, 4 / 33 You did well Standard input processing Testing Debugging
More informationUNIX I/O. Computer Systems: A Programmer's Perspective, Randal E. Bryant and David R. O'Hallaron Prentice Hall, 3 rd edition, 2016, Chapter 10
Reference: Advanced Programming in the UNIX Environment, Third Edition, W. Richard Stevens and Stephen A. Rago, Addison-Wesley Professional Computing Series, 2013. Chapter 3 Computer Systems: A Programmer's
More informationFile I/O. Dong-kun Shin Embedded Software Laboratory Sungkyunkwan University Embedded Software Lab.
1 File I/O Dong-kun Shin Embedded Software Laboratory Sungkyunkwan University http://nyx.skku.ac.kr Unix files 2 A Unix file is a sequence of m bytes: B 0, B 1,..., B k,..., B m-1 All I/O devices are represented
More informationC-Refresher: Session 10 Disk IO
C-Refresher: Session 10 Disk IO Arif Butt Summer 2017 I am Thankful to my student Muhammad Zubair bcsf14m029@pucit.edu.pk for preparation of these slides in accordance with my video lectures at http://www.arifbutt.me/category/c-behind-the-curtain/
More informationOperating Systems 2230
Operating Systems 2230 Computer Science & Software Engineering Lecture 4: Operating System Services All operating systems provide service points through which a general application program may request
More informationSystem Calls and I/O. CS 241 January 27, Copyright : University of Illinois CS 241 Staff 1
System Calls and I/O CS 241 January 27, 2012 Copyright : University of Illinois CS 241 Staff 1 This lecture Goals Get you familiar with necessary basic system & I/O calls to do programming Things covered
More informationLayers in a UNIX System. Create a new process. Processes in UNIX. fildescriptors streams pipe(2) labinstructions
Process Management Operating Systems Spring 2005 Layers in a UNIX System interface Library interface System call interface Lab Assistant Magnus Johansson magnusj@it.uu.se room 1442 postbox 54 (4th floor,
More informationUNIX input and output
UNIX input and output Disk files In UNIX a disk file is a finite sequence of bytes, usually stored on some nonvolatile medium. Disk files have names, which are called paths. We won t discuss file naming
More informationSystem- Level I/O. Andrew Case. Slides adapted from Jinyang Li, Randy Bryant and Dave O Hallaron
System- Level I/O Andrew Case Slides adapted from Jinyang Li, Randy Bryant and Dave O Hallaron 1 Unix I/O and Files UNIX abstracts many things into files (just a series of bytes) All I/O devices are represented
More informationDarshan Institute of Engineering & Technology for Diploma Studies Unit 6
1. What is File management? In real life, we want to store data permanently so that later on we can retrieve it and reuse it. A file is a collection of bytes stored on a secondary storage device like hard
More informationFile IO and command line input CSE 2451
File IO and command line input CSE 2451 File functions Open/Close files fopen() open a stream for a file fclose() closes a stream One character at a time: fgetc() similar to getchar() fputc() similar to
More informationLecture 7: file I/O, more Unix
CIS 330: / / / / (_) / / / / _/_/ / / / / / \/ / /_/ / `/ \/ / / / _/_// / / / / /_ / /_/ / / / / /> < / /_/ / / / / /_/ / / / /_/ / / / / / \ /_/ /_/_/_/ _ \,_/_/ /_/\,_/ \ /_/ \ //_/ /_/ Lecture 7: file
More informationENG120. Misc. Topics
ENG120 Misc. Topics Topics Files in C Using Command-Line Arguments Typecasting Working with Multiple source files Conditional Operator 2 Files and Streams C views each file as a sequence of bytes File
More informationOperating Systems. Lecture 06. System Calls (Exec, Open, Read, Write) Inter-process Communication in Unix/Linux (PIPE), Use of PIPE on command line
Operating Systems Lecture 06 System Calls (Exec, Open, Read, Write) Inter-process Communication in Unix/Linux (PIPE), Use of PIPE on command line March 04, 2013 exec() Typically the exec system call is
More informationCS113: Lecture 7. Topics: The C Preprocessor. I/O, Streams, Files
CS113: Lecture 7 Topics: The C Preprocessor I/O, Streams, Files 1 Remember the name: Pre-processor Most commonly used features: #include, #define. Think of the preprocessor as processing the file so as
More informationContents. Programming Assignment 0 review & NOTICE. File IO & File IO exercise. What will be next project?
File I/O Prof. Jin-Soo Kim(jinsookim@skku.edu) TA - Dong-Yun Lee(dylee@csl.skku.edu) Computer Systems Laboratory Sungkyunkwan University http://csl.skku.edu Contents Programming Assignment 0 review & NOTICE
More informationCMPS 105 Systems Programming. Prof. Darrell Long E2.371
+ CMPS 105 Systems Programming Prof. Darrell Long E2.371 darrell@ucsc.edu + Chapter 3: File I/O 2 + File I/O 3 n What attributes do files need? n Data storage n Byte stream n Named n Non-volatile n Shared
More informationFile Descriptors and Piping
File Descriptors and Piping CSC209: Software Tools and Systems Programming Furkan Alaca & Paul Vrbik University of Toronto Mississauga https://mcs.utm.utoronto.ca/~209/ Week 8 Today s topics File Descriptors
More informationComputer Architecture and Assembly Language. Practical Session 5
Computer Architecture and Assembly Language Practical Session 5 Addressing Mode - "memory address calculation mode" An addressing mode specifies how to calculate the effective memory address of an operand.
More informationPrinceton University Computer Science 217: Introduction to Programming Systems I/O Management
Princeton University Computer Science 7: Introduction to Programming Systems I/O Management From a student's readme: ====================== Stress Testing ====================== To stress out this program,
More informationProcesses often need to communicate. CSCB09: Software Tools and Systems Programming. Solution: Pipes. Recall: I/O mechanisms in C
2017-03-06 Processes often need to communicate CSCB09: Software Tools and Systems Programming E.g. consider a shell pipeline: ps wc l ps needs to send its output to wc E.g. the different worker processes
More informationBIL 104E Introduction to Scientific and Engineering Computing. Lecture 12
BIL 104E Introduction to Scientific and Engineering Computing Lecture 12 Files v.s. Streams In C, a file can refer to a disk file, a terminal, a printer, or a tape drive. In other words, a file represents
More informationFile and Console I/O. CS449 Fall 2017
File and Console I/O CS449 Fall 2017 What is a Unix(or Linux) File? Narrow sense: a resource provided by OS for storing informalon based on some kind of durable storage (e.g. HDD, SSD, DVD, ) Wide (UNIX)
More informationSocket programming in C
Socket programming in C Sven Gestegård Robertz September 2017 Abstract A socket is an endpoint of a communication channel or connection, and can be either local or over the network.
More informationInput and Output System Calls
Chapter 2 Input and Output System Calls Internal UNIX System Calls & Libraries Using C --- 1011 OBJECTIVES Upon completion of this unit, you will be able to: Describe the characteristics of a file Open
More informationInter-Process Communication
CS 326: Operating Systems Inter-Process Communication Lecture 10 Today s Schedule Shared Memory Pipes 2/28/18 CS 326: Operating Systems 2 Today s Schedule Shared Memory Pipes 2/28/18 CS 326: Operating
More informationPrinceton University Computer Science 217: Introduction to Programming Systems. I/O Management
Princeton University Computer Science 7: Introduction to Programming Systems I/O Management Goals of this Lecture Help you to learn about: The C/Unix file abstraction Standard C I/O Data structures & functions
More informationPrinceton University. Computer Science 217: Introduction to Programming Systems. I/O Management
Princeton University Computer Science 7: Introduction to Programming Systems I/O Management Goals of this Lecture Help you to learn about: The C/Unix file abstraction Standard C I/O Data structures & functions
More informationCS 261 Fall Mike Lam, Professor. Structs and I/O
CS 261 Fall 2018 Mike Lam, Professor Structs and I/O Typedefs A typedef is a way to create a new type name Basically a synonym for another type Useful for shortening long types or providing more meaningful
More information