PROGRAMMAZIONE I A.A. 2017/2018

Size: px
Start display at page:

Download "PROGRAMMAZIONE I A.A. 2017/2018"

Transcription

1 PROGRAMMAZIONE I A.A. 2017/2018

2 INPUT/OUTPUT

3 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 input devices such as a keyboard. The C standard library provides numerous functions for these purposes. Often referred as the I/O library All of the basic functions, macros, and types for input and output are declared in the header file stdio.h.

4 STREAMS From the point of view of a C program, all kinds of files and devices for input and output are uniformly represented as logical data streams, regardless of whether the program reads or writes a character or byte at a time, or text lines, or data blocks of a given size. Streams in C can be either text or binary streams Opening a file by means of the function fopen( ) (or tmpfile( )) creates a new stream, which then exists until closed by the fclose( ) function.

5 TEXT STREAMS A text stream transports the characters of a text that is divided into lines. A line of text consists of a sequence of characters ending in a newline character ( \n ). A line of text can also be empty, meaning that it consists of a newline character only. The last line transported may or may not have to end with a newline character, depending on the implementation.

6 TEXT STREAMS The internal representation of text in a C program is the same regardless of the system on which the program is running. üthus text input and output on a given system may involve removing, adding, or altering certain characters. üfor example, on systems that are not Unix-based, end-ofline indicators ordinarily have to be converted into newline characters when reading text files, as on Windows systems, for instance, where the end-of-line indicator is a sequence of two control characters, \r (carriage return) and \n (newline). As the programmer, you generally do not have to worry about the necessary adaptations, because they are performed automatically by the I/O functions in the standard library.

7 BINARY STREAMS A binary stream is a sequence of bytes that are transmitted without modification. In other words, the I/O functions do not involve any interpretation of control characters when operating on binary streams. Data written to a file through a binary stream can always be read back unchanged on the same system. However, in certain implementations there may be additional zerovalued bytes appended at the end of the stream. Binary streams are normally used to write binary data for example, database records without converting it to text.

8 FILES

9 OPENING A FILE A file represents a sequence of bytes. The fopen( ) function associates a file with a stream and initializes an object of the type FILE, which contains all the information necessary to control the stream. Such information includes üa pointer to the buffer used; üa file position indicator, which specifies a position to access in the file;

10 OPENING A FILE Each of the functions that open files namely fopen( ), freopen( ), and tmpfile( ) returns a pointer to a FILE object for the stream associated with the file being opened. Once you have opened a file, you can call functions to transfer data and to manipulate the stream. Such functions have a pointer to a FILE object commonly called a FILE pointer as one of their arguments. üthe FILE pointer specifies the stream on which the operation is carried out.

11 FUNCTIONS WITHOUT OPENING A FILE The I/O library also contains functions that operate on the file system, and take the name of a file as one of their parameters. These functions do not require the file to be opened first. The remove( ) function deletes a file (or an empty directory). The string argument is the file s name. The rename( ) function changes the name of a file (or directory). The function s two string arguments are the old and new names, in that order.

12 EXAMPLE The remove( ) and rename( ) functions both have the return type int, and return zero on success, or a non-zero value on failure. The following statement changes the name of the file songs.dat to mysongs.dat: if ( rename( "songs.dat", "mysongs.dat" )!= 0 ) fprintf( stderr, "Error renaming \"songs.dat\".\n" ); Conditions that can cause the rename( ) function to fail include the following: üno file exists with the old name; üthe program does not have the necessary access privileges; üthe file is open.

13 SEQUENTIAL AND RANDOM ACCESS

14 FILE POSITION Like the elements of a char array, each character in an ordinary file has a definite position in the file. The file position indicator in the object representing the stream determines the position of the next character to be read or written. When you open a file for reading or writing, the file position indicator points to the beginning of the file, so that the next character accessed has the position 0. If you open the file in append mode, the file position indicator may point to the end of the file. Each read or write operation increases the indicator by the number of characters read from the file or written to the file.

15 SEQUENTIAL AND RANDOM ACCESS This behavior makes it simple to process the contents of a file sequentially. Random access within the file is achieved by using functions that change the file position indicator, fseek(), fgetpos( ), and rewind( ). ürewind() sets the file position indicator to the beginning of the file üfgetpos() retrieve the current file position Of course, not all files support changing access positions. Sequential I/O devices such as terminals and printers do not, for example.

16 BUFFERS

17 BUFFERS In working with files, it is generally not efficient to read or write individual characters. For this reason, a stream has a buffer in which it collects characters, which are transferred as a block to or from the file. Sometimes you don t want buffering, however: üfor example, after an error has occurred, you might want to write data to a file as directly as possible.

18 THREE WAYS OF BUFFERING Fully buffered: the characters in the buffer are normally transferred only when the buffer is full. Line-buffered: the characters in the buffer are normally transferred only when a newline character is written to the buffer, or when the buffer is full. Unbuffered: Characters are transferred as promptly as possible.

19 MORE ON BUFFERING You can also explicitly transfer the characters in the stream s output buffer to the associated file by calling the fflush( ) function. The buffer is also flushed when you close a stream, and normal program termination flushes the buffers of all the program s streams. When you open an ordinary file by calling fopen( ), the new stream is fully buffered. After you have opened a file, and before you perform the first input or output operation on it, you can change the buffering mode using the setbuf( ) or setvbuf( ) function.

20 STANDARD STREAMS Three standard text streams are available to every C program on starting. These streams do not have to be explicitly opened. FILE pointer Common name Buffering mode stdin Standard input Line-buffered stdout Standard output Line-buffered stderr Standard error output Unbuffered stdin is usually associated with the keyboard, and stdout and stderr with the console display.

21 EXAMPLE stdout I should print something as Exit from the program\n #include<stdio.h> int main() { int* p= NULL; fprintf(stdout, "I should print something as..."); if (p == NULL) fprintf(stderr, "Pointer is NULL!"); else { *p = 3; fprintf(stdout, "%d\n", *p); fprintf(stdout, "Exit from the program\n"); return 0; stderr Pointer is NULL! Pointer is NULL! I should print something as Exit from the program

22 READING AND WRITING TEXT FILES

23 NEEDED OPERATIONS To write to a new file or modify the contents of an existing file, you must first open the file. When you open a file, you must specify an access mode indicating whether you plan to read, to write, or some combination of the two. When you have finished using a file, close it to release resources.

24 OPENING A FILE: FOPEN() The standard library provides the function fopen() to open a file. FILE *fopen( const char * restrict filename, const char * restrict mode ); This function opens the file whose name is specified by the string filename. üthe filename may contain a directory part. The second argument, mode, is also a string, and specifies the access mode. The fopen( ) function associates the file with a new stream.

25 FREOPEN This function redirects a stream. Like fopen(), freopen() opens the specified file in the specified mode. However, rather than creating a new stream, freopen() associates the file with the existing stream specified by the third argument. The file previously associated with that stream is closed. FILE *freopen( const char * restrictfilename, const char * restrict mode, FILE * restrict stream ); The most common use of freopen() is to redirect the standard streams, stdin, stdout, and stderr.

26 ACCESS MODE The access mode specified by the second argument to fopen( ) or freopen( ) determines what input and output operations the new stream permits. The first character in the mode string is always r for read, w for write, or a for append. The mode string may also contain one or both of the characters + and b üin either order: +b has the same effect as b+. A plus sign (+) in the mode string means that both read and write operations are permitted.

27 OPEN IN BINARY MODE A b in the mode string causes the file to be opened in binary mode that is, the new stream associated with the file is a binary stream. If there is no b in the mode string, the new stream is a text stream.

28 CREATION AND ACCESS MODES If the mode string begins with r, the file must already exist in the file system. If the mode string begins with w, then the file will be created if it does not already exist. If it does exist, its previous contents will be lost, because the fopen( ) function truncates it to zero length in write mode. A mode string beginning with a (for append) also causes the file to be created if it does not already exist. If the file does exist, however, its contents are preserved, because all write operations are automatically performed at the end of the file.

29 FOPEN MODES r - open for reading w - open for writing (file need not exist) a - open for appending (file need not exist) r+ - open for reading and writing, start at beginning w+ - open for reading and writing (overwrite file) a+ - open for reading and writing (append if file exists) Note that it's possible for fopen to fail even if your program is perfectly correct: you might try to open a file specified by the user, and that file might not exist (or it might be write-protected). In those cases, fopen will the NULL pointer.

30 FCLOSE When you're done working with a file, you should close it using the function üint fclose(file *a_file); fclose returns zero if the file is closed successfully. An example of fclose is üfclose(fp); int res= fclose(fp) If (res!= 0) puts( Error while closing files )

31 READING AND WRITING WITH FPRINTF, FSCANF FPUTC, AND FGETC To work with text input and output, you use fprintf() and fscanf(), both of which are similar to printf() and scanf() except that you must pass the FILE pointer as first argument. For example: FILE *fp; fp=fopen( /Users/francescosantini/Desktop/ProgrammI/output.txt", "w"); fprintf(fp, "Testing...\n");

32 FGETC It is also possible to read (or write) a single character at a time--this can be useful if you wish to perform character-by-character input (for instance, if you need to keep track of every piece of punctuation in a file it would make more sense to read in a single character than to read in a string at a time.) The fgetc function, which takes a file pointer, and returns an int, will let you read a single character from a file: üint fgetc (FILE *fp);

33 EXAMPLE #include <stdio.h> int main ( int argc, char *argv[] ) { if ( argc!= 2 ) /* argc should be 2 for correct execution */ { /* We print argv[0] assuming it is the program name */ printf( "usage: %s filename", argv[0] ); else { // We assume argv[1] is a filename to open FILE *file = fopen( argv[1], "r" ); /* fopen returns 0, the NULL pointer, on failure */ if ( file == NULL ) { printf( "Could not open file\n" ); else

34 EXAMPLE 2 else { int x; /* read one character at a time from file, stopping at EOF, which indicates the end of the file. */ while ( ( x = fgetc( file ) )!= EOF ) { printf( "%c", x ); fclose( file );

35 FPUTC The fputc function allows you to write a character at a time, character by character. üint fputc( int c, FILE *fp ); Note that the first argument should be in the range of an unsigned char so that it is a valid character. The second argument is the file to write to. On success, fputc() will return the value c, and on failure, it will return EOF.

36 FSCANF #include<stdio.h> MacBook-Francesco:ProgrammI francescosantini$./main Testing... Testing...10 int main(void) { FILE *fp; int a= 10; fp=fopen("/users/francescosantini/desktop/programmi/output.txt", "r"); if (fp == NULL) { puts("errore"); return -1; char stringread[30]; int returnfscanf= fscanf(fp, "%s", stringread); while (returnfscanf!= EOF) { printf("%s\n", stringread); returnfscanf= fscanf(fp, "%s", stringread); fclose(fp); output.text: Testing Testing...10

37 FSEEK int fseek(file * stream, long int offset, int from); To move the position in the file From can be one among üseek_set 0 SEEK_CUR 1 SEEK_END 2 Which correspond to üthe beginning of the file, üthe current file position, üthe end of the file

38 EXAMPLE #include <stdio.h> This is C Programming Language int main () { FILE *fp; fp = fopen("file.txt","w+"); fputs("this is tutorialspoint.com", fp); fseek( fp, 7, SEEK_SET ); fputs(" C Programming Language", fp); fclose(fp); return(0);

39 READ AND WRITE A program must not alternate immediately between reading and writing. After a write operation, you must call the fflush() function or a positioning function (fseek( )) before performing a read operation. üso you are sure the file is updated before reading it The C library function int fflush(file *stream) flushes the output buffer of a stream. After a read operation, you must call a positioning function before performing a write operation.

40 READING AND WRITING BINARY FILE I/O

41 FWRITE For binary File I/O you use fread and fwrite. The declarations for each are similar: size_t fwrite(const void *ptr, size_t size_of_elements, size_t number_of_elements, FILE *a_file); The first argument is the name of the array or the address of the structure you want to write to the file. The second argument is the size of each element of the array; it is in bytes. The third argument is number of elements. The fourth argument is the pointer to FILE.

42 EXAMPLE #include<stdio.h> int main(void) { FILE *fp; fp=fopen("/users/francescosantini/desktop/programmi/output.bin", wb"); if (fp == NULL) { puts("error fopen"); return -1; int x[4]={1,2,3,4; int res= fwrite(x, sizeof(x[0]), sizeof(x)/sizeof(x[0]), fp); if (res == 0) { puts("error fwrite"); return -1; fclose(fp); return 0;

43 READ FROM A BINARY FILE size_t fread(void *ptr, size_t size_of_elements, size_t number_of_elements, FILE *a_file); Remember that they are not ASCII characters! MacBook-Francesco:ProgrammI francescosantini$ hexdump outbut.bin

44 TMPFILE() FILE *tmpfile( void ); The tmpfile( ) function creates a new temporary file whose name is distinct from all other existing files, and opens the file for binary writing and reading (as if the mode string "wb+" were used in an fopen() call). If the program is terminated normally, the file is automatically deleted. All three file-opening functions return a pointer to the stream opened if successful, or a null pointer to indicate failure.

45 EXAMPLE #include<stdio.h> int main(void) { FILE *fp; rb"); fp=fopen("/users/francescosantini/desktop/programmi/output.bin", if (fp == NULL) { puts("error fopen"); return -1; int a= 0; int res= fread(&a, sizeof(int), 1, fp); if (res == EOF) { puts("error fread"); return -1; else printf("value read: %d\n", a); fclose(fp); return 0;

46 WRITE A STRUCTURE int main() { int counter; FILE *ptr_myfile; struct rec my_record; #include<stdio.h> /* Our structure */ struct rec { int x,y,z; ; ptr_myfile=fopen("test.bin","wb"); if (!ptr_myfile) { printf("unable to open file!"); return 1; for ( counter=1; counter <= 10; counter++) { my_record.x= counter; fwrite(&my_record, sizeof(struct rec), 1, ptr_myfile); fclose(ptr_myfile); return 0;

47 READ A STRUCTURE int main() { int counter; FILE *ptr_myfile; struct rec my_record; #include<stdio.h> /* Our structure */ struct rec { int x,y,z; ; ptr_myfile=fopen("test.bin","rb"); if (!ptr_myfile) { printf("unable to open file!"); return 1; for ( counter=1; counter <= 10; counter++) { fread(&my_record,sizeof(struct rec),1,ptr_myfile); printf("%d\n",my_record.x); fclose(ptr_myfile); return 0;

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

Mode 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 information

Input/Output and the Operating Systems

Input/Output and the Operating Systems Input/Output and the Operating Systems Fall 2015 Jinkyu Jeong (jinkyu@skku.edu) 1 I/O Functions Formatted I/O printf( ) and scanf( ) fprintf( ) and fscanf( ) sprintf( ) and sscanf( ) int printf(const char*

More information

2009 S2 COMP File Operations

2009 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 information

Accessing 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 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 information

25.2 Opening and Closing a File

25.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 information

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

Content. 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 information

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

UNIT-V CONSOLE I/O. This section examines in detail the console I/O functions. UNIT-V Unit-5 File Streams Formatted I/O Preprocessor Directives Printf Scanf A file represents a sequence of bytes on the disk where a group of related data is stored. File is created for permanent storage

More information

CS240: Programming in C

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 information

CS246 Spring14 Programming Paradigm Files, Pipes and Redirection

CS246 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 information

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

CSI 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 information

System Software Experiment 1 Lecture 7

System 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 information

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

CMPE-013/L. File I/O. File Processing. Gabriel Hugh Elkaim Winter File Processing. Files and Streams. Outline. CMPE-013/L Outline File Processing File I/O Gabriel Hugh Elkaim Winter 2014 Files and Streams Open and Close Files Read and Write Sequential Files Read and Write Random Access Files Read and Write Random

More information

Standard File Pointers

Standard 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 information

Systems Programming. 08. Standard I/O Library. Alexander Holupirek

Systems 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 information

Fundamentals of Programming. Lecture 10 Hamed Rasifard

Fundamentals of Programming. Lecture 10 Hamed Rasifard Fundamentals of Programming Lecture 10 Hamed Rasifard 1 Outline File Input/Output 2 Streams and Files The C I/O system supplies a consistent interface to the programmer independent of the actual device

More information

CSC209H Lecture 3. Dan Zingaro. January 21, 2015

CSC209H 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 information

EM108 Software Development for Engineers

EM108 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 information

UNIT IV-2. The I/O library functions can be classified into two broad categories:

UNIT 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 information

C-Refresher: Session 10 Disk IO

C-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 information

Introduction to file management

Introduction 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 information

Input / Output Functions

Input / 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 information

Data File and File Handling

Data 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 information

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

Programming in C. Session 8. Seema Sirpal Delhi University Computer Centre Programming in C Session 8 Seema Sirpal Delhi University Computer Centre File I/O & Command Line Arguments An important part of any program is the ability to communicate with the world external to it.

More information

File I/O. Arash Rafiey. November 7, 2017

File 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 information

File Handling. Reference:

File Handling. Reference: File Handling Reference: http://www.tutorialspoint.com/c_standard_library/ Array argument return int * getrandom( ) static int r[10]; int i; /* set the seed */ srand( (unsigned)time( NULL ) ); for ( i

More information

File IO and command line input CSE 2451

File 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 information

CSci 4061 Introduction to Operating Systems. Input/Output: High-level

CSci 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 information

File I/O. Preprocessor Macros

File 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 information

Files and Streams Opening and Closing a File Reading/Writing Text Reading/Writing Raw Data Random Access Files. C File Processing CS 2060

Files 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 information

Computer programming

Computer programming Computer programming "He who loves practice without theory is like the sailor who boards ship without a ruder and compass and never knows where he may cast." Leonardo da Vinci T.U. Cluj-Napoca - Computer

More information

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

Quick 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 information

Intermediate Programming, Spring 2017*

Intermediate 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 information

Lecture 9: File Processing. Quazi Rahman

Lecture 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 information

M.CS201 Programming language

M.CS201 Programming language Power Engineering School M.CS201 Programming language Lecture 16 Lecturer: Prof. Dr. T.Uranchimeg Agenda Opening a File Errors with open files Writing and Reading File Data Formatted File Input Direct

More information

UNIX System Programming

UNIX 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 information

Week 9 Lecture 3. Binary Files. Week 9

Week 9 Lecture 3. Binary Files. Week 9 Lecture 3 Binary Files 1 Reading and Writing Binary Files 2 Binary Files It is possible to write the contents of memory directly to a file. The bits need to be interpreted on input Possible to write out

More information

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved. C How to Program, 6/e Storage of data in variables and arrays is temporary such data is lost when a program terminates. Files are used for permanent retention of data. Computers store files on secondary

More information

Standard C Library Functions

Standard 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 information

Darshan Institute of Engineering & Technology for Diploma Studies Unit 6

Darshan 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 information

ENG120. Misc. Topics

ENG120. 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 information

C File Processing: One-Page Summary

C File Processing: One-Page Summary Chapter 11 C File Processing C File Processing: One-Page Summary #include int main() { int a; FILE *fpin, *fpout; if ( ( fpin = fopen( "input.txt", "r" ) ) == NULL ) printf( "File could not be

More information

Unit 6 Files. putchar(ch); ch = getc (fp); //Reads single character from file and advances position to next character

Unit 6 Files. putchar(ch); ch = getc (fp); //Reads single character from file and advances position to next character 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 information

Chapter 12. Files (reference: Deitel s chap 11) chap8

Chapter 12. Files (reference: Deitel s chap 11) chap8 Chapter 12 Files (reference: Deitel s chap 11) 20061025 chap8 Introduction of File Data files Can be created, updated, and processed by C programs Are used for permanent storage of large amounts of data

More information

C Basics And Concepts Input And Output

C 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 information

C for Engineers and Scientists: An Interpretive Approach. Chapter 14: File Processing

C for Engineers and Scientists: An Interpretive Approach. Chapter 14: File Processing Chapter 14: File Processing Files and Streams C views each file simply as a sequential stream of bytes. It ends as if there is an end-of-file marker. The data structure FILE, defined in stdio.h, stores

More information

Standard I/O in C, Computer System and programming in C

Standard 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 information

Computer Programming Unit v

Computer Programming Unit v READING AND WRITING CHARACTERS We can read and write a character on screen using printf() and scanf() function but this is not applicable in all situations. In C programming language some function are

More information

C PROGRAMMING. Characters and Strings File Processing Exercise

C PROGRAMMING. Characters and Strings File Processing Exercise C PROGRAMMING Characters and Strings File Processing Exercise CHARACTERS AND STRINGS A single character defined using the char variable type Character constant is an int value enclosed by single quotes

More information

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

Slide Set 8. for ENCM 339 Fall 2017 Section 01. Steve Norman, PhD, PEng Slide Set 8 for ENCM 339 Fall 2017 Section 01 Steve Norman, PhD, PEng Electrical & Computer Engineering Schulich School of Engineering University of Calgary October 2017 ENCM 339 Fall 2017 Section 01 Slide

More information

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

File (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 information

Naked C Lecture 6. File Operations and System Calls

Naked C Lecture 6. File Operations and System Calls Naked C Lecture 6 File Operations and System Calls 20 August 2012 Libc and Linking Libc is the standard C library Provides most of the basic functionality that we've been using String functions, fork,

More information

Ch 11. C File Processing (review)

Ch 11. C File Processing (review) Ch 11 C File Processing (review) OBJECTIVES To create, read, write and update files. Sequential access file processing. Data Hierarchy Data Hierarchy: Bit smallest data item Value of 0 or 1 Byte 8 bits

More information

structs as arguments

structs 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 information

C Programming Language

C Programming Language C Programming Language File Input/Output Dr. Manar Mohaisen Office: F208 Email: manar.subhi@kut.ac.kr Department of EECE Review of the Precedent Lecture Arrays and Pointers Class Objectives What is a File?

More information

File and Console I/O. CS449 Spring 2016

File 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 information

File Processing. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan

File Processing. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan File Processing Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan Outline 11.2 The Data Hierarchy 11.3 Files and Streams 11.4 Creating a Sequential

More information

C programming basics T3-1 -

C programming basics T3-1 - C programming basics T3-1 - Outline 1. Introduction 2. Basic concepts 3. Functions 4. Data types 5. Control structures 6. Arrays and pointers 7. File management T3-2 - 3.1: Introduction T3-3 - Review of

More information

CAAM 420 Notes Chapter 2: The C Programming Language

CAAM 420 Notes Chapter 2: The C Programming Language CAAM 420 Notes Chapter 2: The C Programming Language W. Symes and T. Warburton October 2, 2013 22 Stack Overflow Just for warmup, here is a remarkable memory bust: 1 / Author : WWS 3 Purpose : i l l u

More information

Computer System and programming in C

Computer System and programming in C File Handling in C What is a File? A file is a collection of related data that a computers treats as a single unit. Computers store files to secondary storage so that the contents of files remain intact

More information

fopen() fclose() fgetc() fputc() fread() fwrite()

fopen() 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 information

Lecture 8. Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson)

Lecture 8. Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson) Lecture 8 Data Files Dr M Kasim A Jalil Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson) Objectives In this chapter, you will learn: To be able to create, read, write and update

More information

Chapter 11 File Processing

Chapter 11 File Processing 1 Chapter 11 File Processing Copyright 2007 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 2 Chapter 11 File Processing Outline 11.1 Introduction 11.2 The Data Hierarchy 11.3

More information

Goals of this Lecture

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 system-level

More information

CSI 402 Systems Programming LECTURE 4 FILES AND FILE OPERATIONS

CSI 402 Systems Programming LECTURE 4 FILES AND FILE OPERATIONS CSI 402 Systems Programming LECTURE 4 FILES AND FILE OPERATIONS A mini Quiz 2 Consider the following struct definition struct name{ int a; float b; }; Then somewhere in main() struct name *ptr,p; ptr=&p;

More information

UNIX Shell. The shell sits between you and the operating system, acting as a command interpreter

UNIX Shell. The shell sits between you and the operating system, acting as a command interpreter Shell Programming Linux Commands UNIX Shell The shell sits between you and the operating system, acting as a command interpreter The user interacts with the kernel through the shell. You can write text

More information

I/O Management! Goals of this Lecture!

I/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 information

I/O Management! Goals of this Lecture!

I/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 information

Introduction to Computer Programming Lecture 18 Binary Files

Introduction to Computer Programming Lecture 18 Binary Files Introduction to Computer Programming Lecture 18 Binary Files Assist.Prof.Dr. Nükhet ÖZBEK Ege University Department of Electrical&Electronics Engineering nukhet.ozbek@ege.edu.tr 1 RECALL: Text File Handling

More information

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

CSE2301. 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 information

Files. Programs and data are stored on disk in structures called files Examples. a.out binary file lab1.c - text file term-paper.

Files. Programs and data are stored on disk in structures called files Examples. a.out binary file lab1.c - text file term-paper. File IO part 2 Files Programs and data are stored on disk in structures called files Examples a.out binary file lab1.c - text file term-paper.doc - binary file Overview File Pointer (FILE *) Standard:

More information

HIGH LEVEL FILE PROCESSING

HIGH LEVEL FILE PROCESSING HIGH LEVEL FILE PROCESSING 1. Overview The learning objectives of this lab session are: To understand the functions used for file processing at a higher level. o These functions use special structures

More information

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

File 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 information

CP2 Revision. theme: file access and unix programs

CP2 Revision. theme: file access and unix programs CP2 Revision theme: file access and unix programs file access in C basic access functionality: FILE *fopen(const char *filename, const char *mode); This function returns a pointer to a file stream (or

More information

Chapter 5, Standard I/O. Not UNIX... C standard (library) Why? UNIX programmed in C stdio is very UNIX based

Chapter 5, Standard I/O. Not UNIX... C standard (library) Why? UNIX programmed in C stdio is very UNIX based Chapter 5, Standard I/O Not UNIX... C standard (library) Why? UNIX programmed in C stdio is very UNIX based #include FILE *f; Standard files (FILE *varname) variable: stdin File Number: STDIN_FILENO

More information

LANGUAGE OF THE C. C: Part 6. Listing 1 1 #include <stdio.h> 2 3 int main(int argc, char *argv[]) PROGRAMMING

LANGUAGE OF THE C. C: Part 6. Listing 1 1 #include <stdio.h> 2 3 int main(int argc, char *argv[]) PROGRAMMING C: Part 6 LANGUAGE OF THE C In part 6 of Steve Goodwins C tutorial we continue our look at file handling and keyboard input File handling Most software will at some time need to read from (or perhaps write

More information

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 12

BIL 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 information

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

Introduction to Computer and Program Design. Lesson 6. File I/O. James C.C. Cheng Department of Computer Science National Chiao Tung University Introduction to Computer and Program Design Lesson 6 File I/O James C.C. Cheng Department of Computer Science National Chiao Tung University File System in OS Microsoft Windows Filename DriveID : /DirctoryName/MainFileName.ExtensionName

More information

UNIT- 2. Binary File

UNIT- 2. Binary File UNIT- 2 Binary Files Structure: 2.1 Classification Of Files 2.2 Files Modes 2.3 Standard Library Functions for Files 2.4 File Type Conversion 2.1 Classification Of Files A file is collection of data. A

More information

System Programming. Standard Input/Output Library (Cont d)

System Programming. Standard Input/Output Library (Cont d) Content : by Dr. B. Boufama School of Computer Science University of Windsor Instructor: Dr. A. Habed adlane@cs.uwindsor.ca http://cs.uwindsor.ca/ adlane/60-256 Content Content 1 Binary I/O 2 3 4 5 Binary

More information

Physical Files and Logical Files. Opening Files. Chap 2. Fundamental File Processing Operations. File Structures. Physical file.

Physical 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 information

Basic and Practice in Programming Lab 10

Basic and Practice in Programming Lab 10 Basic and Practice in Programming Lab 10 File (1/4) File management in C language FILE data type (strictly, data structure in C library) Three operational modes Read/Write/Append fopen A library function

More information

Lecture6 File Processing

Lecture6 File Processing 1 Lecture6 File Processing Dr. Serdar ÇELEBİ 2 Introduction The Data Hierarchy Files and Streams Creating a Sequential Access File Reading Data from a Sequential Access File Updating Sequential Access

More information

Preprocessing directives are lines in your program that start with `#'. The `#' is followed by an identifier that is the directive name.

Preprocessing directives are lines in your program that start with `#'. The `#' is followed by an identifier that is the directive name. Unit-III Preprocessor: The C preprocessor is a macro processor that is used automatically by the C compiler to transform your program before actual compilation. It is called a macro processor because it

More information

Lecture 03 Bits, Bytes and Data Types

Lecture 03 Bits, Bytes and Data Types Lecture 03 Bits, Bytes and Data Types Computer Languages A computer language is a language that is used to communicate with a machine. Like all languages, computer languages have syntax (form) and semantics

More information

C Programming 1. File Access. Goutam Biswas. Lect 29

C Programming 1. File Access. Goutam Biswas. Lect 29 C Programming 1 File Access C Programming 2 Standard I/O So far all our I/O operations are read from the standard input (stdin - keyboard) and write to the standard output (stdout - VDU) devices. These

More information

a = ^ ^ ^ ^ ^ ^ ^ b = c = a^b =

a = ^ ^ ^ ^ ^ ^ ^ b = c = a^b = a = b = ^ ^ ^ ^ ^ ^ ^ ^ c=a^b= & a&b a b ^ a^b &= a &= b = a = b ^= a ^= b >b >>= a >>= b

More information

File System User API

File 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 information

Computer Programming: Skills & Concepts (CP) Files in C

Computer Programming: Skills & Concepts (CP) Files in C CP 20 slide 1 Tuesday 21 November 2017 Computer Programming: Skills & Concepts (CP) Files in C Julian Bradfield Tuesday 21 November 2017 Today s lecture Character oriented I/O (revision) Files and streams

More information

CS 261 Fall Mike Lam, Professor. Structs and I/O

CS 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

Basic I/O. COSC Software Tools. Streams. Standard I/O. Standard I/O. Formatted Output

Basic I/O. COSC Software Tools. Streams. Standard I/O. Standard I/O. Formatted Output Basic I/O COSC2031 - Software Tools C - Input/Output (K+R Ch. 7) We know how to do some basic input and output: getchar - reading characters putchar - writing characters printf - formatted output Input

More information

Lecture 8: Structs & File I/O

Lecture 8: Structs & File I/O ....... \ \ \ / / / / \ \ \ \ / \ / \ \ \ V /,----' / ^ \ \.--..--. / ^ \ `--- ----` / ^ \. ` > < / /_\ \. ` / /_\ \ / /_\ \ `--' \ /. \ `----. / \ \ '--' '--' / \ / \ \ / \ / / \ \ (_ ) \ (_ ) / / \ \

More information

Programming & Data Structure

Programming & Data Structure File Handling Programming & Data Structure CS 11002 Partha Bhowmick http://cse.iitkgp.ac.in/ pb CSE Department IIT Kharagpur Spring 2012-2013 File File Handling File R&W argc & argv (1) A file is a named

More information

8. Structures, File I/O, Recursion. 18 th October IIT Kanpur

8. Structures, File I/O, Recursion. 18 th October IIT Kanpur 8. Structures, File I/O, Recursion 18 th October IIT Kanpur C Course, Programming club, Fall 2008 1 Basic of Structures Definition: A collection of one or more different variables with the same handle

More information

CSC 270 Survey of Programming Languages. Input and Output

CSC 270 Survey of Programming Languages. Input and Output CSC 270 Survey of Programming Languages C Lecture 8 Input and Output Input and Output C supports 2 different I/O libraries: buffered (higher level functions supported by ANSI standards) unbuffered (lower-level

More information

DS: CS Computer Sc & Engg: IIT Kharagpur 1. File Access. Goutam Biswas. ect 29

DS: CS Computer Sc & Engg: IIT Kharagpur 1. File Access. Goutam Biswas. ect 29 DS: CS 11002 Computer Sc & Engg: IIT Kharagpur 1 File Access DS: CS 11002 Computer Sc & Engg: IIT Kharagpur 2 Standard I/O So far all our I/O operations are read from the standard input (stdin - keyboard)

More information

Computer Programming: Skills & Concepts (CP1) Files in C. 18th November, 2010

Computer Programming: Skills & Concepts (CP1) Files in C. 18th November, 2010 Computer Programming: Skills & Concepts (CP1) Files in C 18th November, 2010 CP1 26 slide 1 18th November, 2010 Today s lecture Character oriented I/O (revision) Files and streams Opening and closing files

More information

File and Console I/O. CS449 Fall 2017

File 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 information

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)

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) 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 information

CSI 402 Lecture 2 (More on Files) 2 1 / 20

CSI 402 Lecture 2 (More on Files) 2 1 / 20 CSI 402 Lecture 2 (More on Files) 2 1 / 20 Files A Quick Review Type for file variables: FILE * File operations use functions from stdio.h. Functions fopen and fclose for opening and closing files. Functions

More information

Lecture 7: file I/O, more Unix

Lecture 7: file I/O, more Unix CIS 330: / / / / (_) / / / / _/_/ / / / / / \/ / /_/ / `/ \/ / / / _/_// / / / / /_ / /_/ / / / / /> < / /_/ / / / / /_/ / / / /_/ / / / / / \ /_/ /_/_/_/ _ \,_/_/ /_/\,_/ \ /_/ \ //_/ /_/ Lecture 7: file

More information