Memory Management and
|
|
- Ami McLaughlin
- 6 years ago
- Views:
Transcription
1 Introduction to Computer and Program Design Lesson 6 Memory Management and File I/O James C.C. Cheng Department of Computer Science National Chiao Tung University
2 Dynamic memory allocation l malloc Syntax: #include <stdlib.h> void* malloc( size_t n ); where the size_t is the same as unsigned int malloc() returns a pointer to a chunk of memory of n bytes, or NULL if there is an error. The memory pointed to will be on the heap, not the stack, so make sure to free it when you are done with it. The returned pointer must be typecast l free Syntax: #include <stdlib.h> void free( void* ptr ); free() deallocates the space pointed to by ptr, freeing it up for future use. ptr must be NULL or used in a previous call to malloc(), otherwise a runtime error will occur on free(). 2
3 Dynamic memory allocation l calloc Syntax: #include <stdlib.h> void* calloc (size_t unit, size_t n ); calloc() returns a pointer to a chunk of memory of unit * n bytes with elements initialized t zero, or NULL if there is an error. The returned pointer must be typecast 3
4 Dynamic memory allocation l Example: char *pc = (char *)malloc(10); // 10 characters int *pi = (int *)malloc(sizeof(int) * 10); // 10 integers double *pd = (double *)malloc(80); // 10 doubles if( pc!= NULL && pi!= NULL && pd!= NULL){ // Check the allocation for(int i=0; i<10; ++i) pd[i] = pi[i] = pc[i] = i + 65; for(int i=0; i<10; ++i) printf("%c, %d, %f\n", pc[i], pi[i], pd[i]); // A~J } free(pc); free(pi); free(pd); l free a NULL pointer int *p; // Non-NULL free(p); // Runtime error! p = NULL; free(p); // OK! 4
5 Dynamic memory allocation int n = 1024 * 1024 * 128; // 128 MB double rtime; clock_t clk0, clk1; char *pc = (char *)malloc(n); // clk0 = clock(); for(int i=0; i<n; ++i) pc[i] = 0; clk1 = clock(); rtime = (double)(clk1 - clk0) / (double)clocks_per_sec; printf("iterative clearing time: %f\n", rtime); // The time is proportional to n free(pc); clk0 = clock(); pc = (char *)calloc(1,n); // re-allocating with initialization clk1 = clock(); rtime = (double)(clk1 - clk0) / (double)clocks_per_sec; printf("calloc time: %f\n", rtime); // it's constant time if the hardware supports calloc free(pc); 5
6 Dynamic memory allocation l Memory leaks and dangling Normal allocation Pointer Memory Memory leaks Memory dangling Pointer Memory Pointer Memory 6
7 Dynamic memory allocation l Memory Leaks There is no any pointer to point a allocated memory space Executing the system monitor to watch the memory usage Using two threads to execute the following program If the memory usage approach to the limitation, just stop the program char key = 0, end = 0; do{ // Create 64M byte for input buffer int n = 1024 * 1024 * 64; char *pc =(char *)malloc(n); memset(pc, 0, n); // Clear all data scanf("%s", pc); key = pc[0]; end = pc[1]; }while(key!= 'q' && key!='q' end!= 0); If the OS does not provide Garbage Collection, the allocated memory will never be released. Notice that the timing for releasing by garbage collection is when the program has been terminated. 7
8 Dynamic memory allocation l Memory Dangling A pointer points an unallocated memory space char *pc; *pc = 100; // Dangling pc = (char *)malloc(12); int *pi = (int *)pc; free(pi); *pc = 50; // Dangling 8
9 Dynamic memory allocation l Memory Manipulation Functions memset, memory setting: #include <memory.h> or #include <string.h> void* memset( void *dest, int c, size_t count ); Ø dest: the destination pointer Ø c: set the value, c & 0xFF, to each byte of dest Ø count: the number of byte to set Ø returns the value of dest int n = 3; int *p = (int *)malloc(sizeof(int)*n); memset(p, 0, sizeof(int)*n); for(int i=0; i<n; ++i) printf("%d, 0x%0X\n", p[i], p[i]); memset(p, 255, sizeof(int)*n); for(int i=0; i<n; ++i) printf("%d, 0x%0X\n", p[i], p[i]); memset(p, 65537, sizeof(int)*n); for(int i=0; i<n; ++i) printf("%d, 0x%0X\n", p[i], p[i]); memset((int *)memset(p, 0, 12) + 1, 255, 4) ; for(int i=0; i<n; ++i) printf("%d, 0x%0X\n", p[i], p[i]); 9
10 Dynamic memory allocation l Memory Manipulation Functions The needed time of memset int n = 1024 * 1024 * 128; // 128 MB double rtime; clock_t clk0, clk1; char *pc = (char *)malloc(n); clk0 = clock(); for(int i=0; i<n; ++i) pc[i] = 0; clk1 = clock(); rtime = (double)(clk1 - clk0) / (double)clocks_per_sec; printf("iterative clearing time: %f\n", rtime); // The needed time is proportional to n clk0 = clock(); memset(pc, 0, n); clk1 = clock(); rtime = (double)(clk1 - clk0) / (double)clocks_per_sec; printf("memset time: %f\n", rtime); /* The needed time is still proportional to n but less than iterative method */ free(pc); 10
11 Dynamic memory allocation l Memory Manipulation Functions memcpy, memory copy: #include <memory.h> or #include <string.h> void* memcpy(void *dest, const void *src, size_t count ); dest: the destination pointer src: the source pointer count: the number of byte to copy returns the value of dest If the source and destination overlap, this function does not ensure that the original source bytes in the overlapping region are copied before being overwritten. char s1[] = "Hello! My friend!"; // Why use char[]? const char *s2 = "Hi! Guys."; // Why use const char*? memcpy(s1+7, s2+4, 6); printf("%s\n", s1); // Hello! Guys. memcpy(s1+5, s1+7, 4); printf("%s\n", s1); // Maybe HelloGuysys., maybe not 11
12 Dynamic memory allocation l Memory Manipulation Functions memmove, memory move: #include <string.h> void *memmove( void *dest, const void *src, size_t count ); dest: the destination pointer src: the source pointer count: the number of byte to move returns the value of dest It is similar to memcpy, but memmove ensures the copy of overlapping region. char s1[] = "; memcpy(s1 + 2, s1, 5); printf("%s\n", s1); //
13 Dynamic memory allocation l Memory Manipulation Functions memcmp, memory compare: #include <memory.h> or #include <string.h> int memcmp( const void *buf1, const void *buf2, size_t n ); Ø buf1 and buf2: the pointers of memory Ø n: the number of byte to compare Ø Return Value: relationship of first n bytes of buf1 and buf2 < 0: buf1 less than buf2 0: buf1 identical to buf2 > 0: buf1 greater than buf2 char first[] = " "; char second[] = " "; printf( %d\n, memcmp( first, second, 19 ) ); // 0 printf( %d\n, memcmp( first, second, 20 ) ); // -1 printf( %d\n, memcmp( first + 2, second, 18 ) ); // 1 13
14 Dynamic memory allocation l Dynamic multi-dimension array int m=0, n=0,i,j; scanf("%d %d", &m, &n); int **pp = (int **)malloc(sizeof(int *) * m); for(i=0; i<m; ++i) pp[i] = (int *)malloc(sizeof(int) * n); for(i=0; i<m; ++i) for(j=0; j<n; ++j) pp[i][j] = i * 10 + j; for(i=0; i<m; ++i){ for(j=0; j<n; ++j) printf("%2d, ", pp[i][j]); printf("\n"); } /* Do not forget to free the allocated memory in reverse order of dimension */ for(i=0; i<m; ++i) free(pp[i]); free(pp); 14
15 Linked Lists l Linked List It consists of a sequence of data items such that in each item there is a pointer or a reference to link the next item. The memory addresses of elements may not be adjacent struct Node{ int data; Node *next; }; Node* NewNode(int data){ Node *p = (Node *)calloc(sizeof(node), 1); p->data = data; return p; } Node *phead = NewNode(0), *p = phead; for( int i=1; i<5; ++i, p = p->next) data next p->next = NewNode(i); // Creating the list p = phead; while(p!= NULL) { printf("%d\n", p->data); Node *ptmp = p; p = p->next; free(ptmp); // Release each item } 15
16 Linked Lists l Doubly-Linked List Each node has two pointers, one points the next node and the other points the previous node. struct Node{ int data; Node *next, *prev;}; Node* NewNode(int data){ Node *p = (Node *)calloc(sizeof(node), 1); } p->data = data; return p; Node *phead = NewNode(0); Node *p = phead; for( int i=1; i<5; ++i, p = p->next){ p->next = NewNode(i); p->next->prev = p; } while(p!= NULL) { printf("%d\n", p->data); Node *ptmp = p; p = p->prev; } p = phead; while(p!= NULL) { printf("%d\n", p->data); Node *ptmp = p; p = p->next; free(ptmp); // Release }
17 Arrays vs. Linked Lists l Performances Random access Push back Array: O(1) Dynamic Array: O(1) Doubly-Linked list: O(n) Doubly-Linked list: O(1) Random insertion Pop back Array: O(n) Dynamic Array: O(1) Doubly-Linked list: Doubly-Linked list: O(1) Search time + O(1) Random remove Push front Dynamic Array: O(n) Array: O(n) Doubly-Linked list: O(1) Doubly-Linked list: Search time + O(1) Pop front Dynamic Array: O(n) Doubly-Linked list: O(1) where n is the number of data elements 17
18 Arrays vs. Linked Lists l Performances Resize (from n to m) Array: O(m) Doubly-Linked list: O(m) Clear Array: O(n) n m Copy assignment Array: O(n) Doubly-Linked list: O(n) = Doubly-Linked list: O(n) Concatenation Array: O(n) Doubly-Linked list: O(1) Swap Array: O(n) Doubly-Linked list: O(1) 18
19 File System in OS l Microsoft Windows Filename DriveID : /DirctoryName/MainFileName.ExtensionName EX: Ø C:/test.txt Ø D:/MyDoc/Reports/ ppt Storage Devices Directories or Folders Files Files Directories or Folders Files 19
20 File System in OS l Microsoft Windows Filename DriveID Ø A and B are used for floppy disk drivers Ø C is the master boot device DirctoryName MainFileName ExtensionName = type name Path Absolute path = full path, Relative path Ø a path relative to the working directory Ø EX: if the the working directory is D:/ICP/2011 p ABC.h è D:/ICP/2011/ABC.h p /0515/test.dat è D:/ICP/2011/0515/test.dat p../xyz.txt è D:/ICP/xyz.txt (.. represents the parent diretory) p../../t_t.b è D:/T_T.b 20
21 File System in OS l Microsoft Windows FAT32 (File Allocation Table 32-bit) Max. file size: 4GB Max. length of MainFileName: 255 (in Windows), 8+3(DOS) Protection: Read-Only, Hidden and System exfat (Extended File Allocation Table) Max. file size: 64ZebiB = 2 70 bytes Max. length of MainFileName: 255 Protection: Read-Only, Hidden and System NTFS (New Technology File System) Max. file size: 16 TB Max. length of MainFileName: 255 UTF-16 code units Protection: Read-Only, Hidden, System and Windows Access Control List(ACL) 21
22 File I/O in C l I/O redirection Redirect the standard I/O to file I/O < input redirection > output redirection EX: MyProg.exe < input.txt > ouput.txt #include <stdio.h> void main(){ int x = 0, y = 0; do{ scanf("%d %d", &x, &y); printf("x = %d, y = %d, x * y = %d\n", x, y, x*y); }while( x>=0); } 22
23 File I/O in C l I/O redirection int fprintf(file *stream, const char *format [, argument ]...); stream is a pointer to point a I/O device It returns the number of bytes written. It returns -1 if function failed. #include <stdio.h> void main(){ int x = 10, y = 20; int r = printf("%d, %d\n", x, y); // 10, 20\n printf ("%d\n", r); // 7 r = fprintf( stdout, "%d, %d\n", x, y); // 10, 20\n printf ("%d\n", r); // 7 r = fprintf( stderr, "%d, %d\n", x, y); // 10, 20\n printf ("%d\n", r); // 7 } r = fprintf( stdin, "%d, %d\n", x, y); // printf ("%d\n", r); // -1 23
24 File I/O in C l Stream I/O 1. Open file FILE * file; file = fopen( "C:/MyDoc/data.txt", "r" ); /* filename format: DriveID : /DirctoryName/MainFileName.ExtensionName Each sub-directory name separated by a slash */ // Do not use the back-slash in filename, why? file = fopen( "C:\MyDoc\data.txt", "r" ); 2. Input (read) 3. Output (write) 4. Close file int x[10]; fread( &x, sizeof( int ), 10, file ); char *s = " Hello world"; fwrite( s, 1, strlen(s), file ); fclose(file); 24
25 File I/O in C l Stream I/O Open file FILE *fopen( const char *filename, const char *mode ); mode can be: Ø Ø Ø "r Opens for reading. The file must be existed. "w Opens an empty file for writing. If the given file exists, its contents are destroyed. "a Opens for appending; creates the file first if it doesn t exist. n Writing always at the end of the file (appending) Ø Ø Ø "r+ = r with writing. (The file must exist.) "w+ = w with reading "a+ = a with reading. 25
26 File I/O in C l Stream I/O Open file FILE *fopen( const char *filename, const char *mode ); mode with translation type : Ø mode + t : Open in text mode. (In MS Windows) n It inserts \r (0x0D) before \n (0x0A) in write-out data. n It discard \r (0x0D) before \n (0x0A) in read-in data. n EX: "rt", "wt", "at", "r+t", "w+t", "a+t" Ø mode + b : Open in binary mode. n EX: "rb", "wb", "ab", "r+b", "w+b", "a+b Ø t + mode and b + mode are wrong usages and fopen returns NULL n EX: bw, ta, Ø The default translation type depends on the OS. n You should explicitly specify the translation type at any time. 26
27 l File I/O in C Stream I/O fgec/fputc int fgetc(file *); int fputc(int, FILE*); è returns the character read/written if OK; Otherwise EOF fgets/fputs char * fgetc(char *, FILE *); è returns the result string if OK; Otherwise NULL int fputc(const char *, FILE*); è returns non-negative value if OK; Otherwise 27
28 l File I/O in C Stream I/O fread/fwrite size_t fread( void *buffer, size_t size, size_t count, FILE *stream ); size_t fwrite( const void *buffer, size_t size, size_t count, FILE *stream ); buffer : Storage location for data size: Item size in bytes count: Maximum number of items read/written stream: Pointer to the FILE structure è returns the number of full items actually read/written 28
29 File I/O in C l Stream I/O #include <stdio.h> #include <string.h> int main(){ FILE *pf = fopen("a.txt", "wt"); // try "wb" if(pf!= NULL){ char s[] = "Hello\nworld!\n"; fwrite(s, 1, strlen(s), pf); } fclose(pf); } pf = fopen("a.txt", "rt"); int c = 0; while( (c = fgetc(pf))!= EOF) printf("%02x ", c); printf("\n"); fclose(pf); // try "rb" 29
30 File I/O in C l Stream I/O Other Stream I/O functions: long ftell( FILE *stream ); Ø Gets the current position of a file pointer. int fseek( FILE *stream, long offset, int origin ); Ø Moves the file pointer to a specified location. Ø Origin = SEEK_CUR è current position + offset SEEK_ENDè files size(in byte) + offset SEEK_SET è offset int feof( FILE *stream ); Ø Returns true if the cursor is at the end of file int fprintf( FILE *stream, const char *format [, argument ]...); int fscanf( FILE *stream, const char *format [, argument ]...);
31 List Files In Directory l dirent.h #include <stdio.h> #include <dirent.h> int main(){ DIR *dirp; dirent *entry; if(dirp = opendir("c:/")){ while(entry = readdir (dirp)) printf("%s\n", entry->d_name); closedir (dirp); } getchar(); return 0; } dirent.h is known to be included in the following compilers: Turbo C++ (DOS) GCC (Cross-platform) MinGW (Microsoft Windows) Borland C++ Builder (Microsoft Windows) Microsoft Visual C++ does not include dirent.h Download the API package:
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 informationLesson 4 struct and memory management
Introduction to Computer and Program Design Lesson 4 struct and memory management James C.C. Cheng Department of Computer Science National Chiao Tung University enum l Enumerators Grouping the constant
More informationMemory Management and
Introduction to Computer and Program Design Lesson 5 Memory Management and File I/O James C.C. Cheng Department of Computer Science National Chiao Tung University Dynamic memory allocation l malloc Syntax:
More informationC mini reference. 5 Binary numbers 12
C mini reference Contents 1 Input/Output: stdio.h 2 1.1 int printf ( const char * format,... );......................... 2 1.2 int scanf ( const char * format,... );.......................... 2 1.3 char
More informationMemory Allocation. General Questions
General Questions 1 Memory Allocation 1. Which header file should be included to use functions like malloc() and calloc()? A. memory.h B. stdlib.h C. string.h D. dos.h 2. What function should be used to
More informationCS240: 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 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 informationCSCI 171 Chapter Outlines
Contents CSCI 171 Chapter 1 Overview... 2 CSCI 171 Chapter 2 Programming Components... 3 CSCI 171 Chapter 3 (Sections 1 4) Selection Structures... 5 CSCI 171 Chapter 3 (Sections 5 & 6) Iteration Structures
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 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 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 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 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 informationHIGH 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 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 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 informationInput/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 informationStream Model of I/O. Basic I/O in C
Stream Model of I/O 1 A stream provides a connection between the process that initializes it and an object, such as a file, which may be viewed as a sequence of data. In the simplest view, a stream object
More informationLibrary Functions. General Questions
1 Library Functions General Questions 1. What will the function rewind() do? A. Reposition the file pointer to a character reverse. B. Reposition the file pointer stream to end of file. C. Reposition the
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 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 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 informationCSI 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 informationC 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 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 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 informationCMPE-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 informationComputer 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 informationPointers and File Handling
1 Pointers and File Handling From variables to their addresses Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR 2 Basics of Pointers INDIAN INSTITUTE OF TECHNOLOGY
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 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 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 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 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 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 informationContents. A Review of C language. Visual C Visual C++ 6.0
A Review of C language C++ Object Oriented Programming Pei-yih Ting NTOU CS Modified from www.cse.cuhk.edu.hk/~csc2520/tuto/csc2520_tuto01.ppt 1 2 3 4 5 6 7 8 9 10 Double click 11 12 Compile a single source
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 informationProgramming 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 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 informationECE 264 Exam 2. 6:30-7:30PM, March 9, You must sign here. Otherwise you will receive a 1-point penalty.
ECE 264 Exam 2 6:30-7:30PM, March 9, 2011 I certify that I will not receive nor provide aid to any other student for this exam. Signature: You must sign here. Otherwise you will receive a 1-point penalty.
More informationC 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 informationMARKS: Q1 /20 /15 /15 /15 / 5 /30 TOTAL: /100
FINAL EXAMINATION INTRODUCTION TO ALGORITHMS AND PROGRAMMING II 03-60-141-01 U N I V E R S I T Y O F W I N D S O R S C H O O L O F C O M P U T E R S C I E N C E Winter 2014 Last Name: First Name: Student
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 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 informationProgramming. Pointers, Multi-dimensional Arrays and Memory Management
Programming Pointers, Multi-dimensional Arrays and Memory Management Summary } Computer Memory } Pointers } Declaration, assignment, arithmetic and operators } Casting and printing pointers } Relationship
More informationC 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 informationC 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 informationCSC 1600 Memory Layout for Unix Processes"
CSC 16 Memory Layout for Unix Processes" 1 Lecture Goals" Behind the scenes of running a program" Code, executable, and process" Memory layout for UNIX processes, and relationship to C" : code and constant
More informationAdvanced C Programming and Introduction to Data Structures
FYBCA Semester II (Advanced C Programming and Introduction to Data Structures) Question Bank Multiple Choice Questions Unit-1 1. Which operator is used with a pointer to access the value of the variable
More informationPRINCIPLES OF OPERATING SYSTEMS
PRINCIPLES OF OPERATING SYSTEMS Tutorial-1&2: C Review CPSC 457, Spring 2015 May 20-21, 2015 Department of Computer Science, University of Calgary Connecting to your VM Open a terminal (in your linux machine)
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 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 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 informationTHE C STANDARD LIBRARY & MAKING YOUR OWN LIBRARY. ISA 563: Fundamentals of Systems Programming
THE C STANDARD LIBRARY & MAKING YOUR OWN LIBRARY ISA 563: Fundamentals of Systems Programming Announcements Homework 2 posted Homework 1 due in two weeks Typo on HW1 (definition of Fib. Sequence incorrect)
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 informationC 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 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 informationLecture 8 Dynamic Memory Allocation
Lecture 8 Dynamic Memory Allocation CS240 1 Memory Computer programs manipulate an abstraction of the computer s memory subsystem Memory: on the hardware side 3 @ http://computer.howstuffworks.com/computer-memory.htm/printable
More informationC 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 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 informationUNIT-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 informationHigh Performance Programming Programming in C part 1
High Performance Programming Programming in C part 1 Anastasia Kruchinina Uppsala University, Sweden April 18, 2017 HPP 1 / 53 C is designed on a way to provide a full control of the computer. C is the
More informationKurt Schmidt. October 30, 2018
to Structs Dept. of Computer Science, Drexel University October 30, 2018 Array Objectives to Structs Intended audience: Student who has working knowledge of Python To gain some experience with a statically-typed
More informationComputer 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 informationIntroduction to C Programming (Part C) Copyright 2008 W. W. Norton & Company. All rights Reserved
Introduction to C Programming (Part C) Copyright 2008 W. W. Norton & Company. All rights Reserved Overview (King Ch. 13, 22, 16-17) Strings (Ch. 13) Input/Output (Ch. 22) Structures (Ch. 16) Dynamic memory
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 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 informationThis code has a bug that allows a hacker to take control of its execution and run evilfunc().
Malicious Code Insertion Example This code has a bug that allows a hacker to take control of its execution and run evilfunc(). #include // obviously it is compiler dependent // but on my system
More informationIn Java we have the keyword null, which is the value of an uninitialized reference type
+ More on Pointers + Null pointers In Java we have the keyword null, which is the value of an uninitialized reference type In C we sometimes use NULL, but its just a macro for the integer 0 Pointers are
More informationDynamic Memory. Dynamic Memory Allocation Strings. September 18, 2017 Hassan Khosravi / Geoffrey Tien 1
Dynamic Memory Dynamic Memory Allocation Strings September 18, 2017 Hassan Khosravi / Geoffrey Tien 1 Pointer arithmetic If we know the address of the first element of an array, we can compute the addresses
More informationUnit 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 informationChapter 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 informationNaked 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 informationChapter 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 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 informationCSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community
CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community http://csc.cs.rit.edu History and Evolution of Programming Languages 1. Explain the relationship between machine
More informationDynamic memory allocation (malloc)
1 Plan for today Quick review of previous lecture Array of pointers Command line arguments Dynamic memory allocation (malloc) Structures (Ch 6) Input and Output (Ch 7) 1 Pointers K&R Ch 5 Basics: Declaration
More informationECE551 Midterm Version 2
Name: ECE551 Midterm Version 2 NetID: There are 7 questions, with the point values as shown below. You have 75 minutes with a total of 75 points. Pace yourself accordingly. This exam must be individual
More informationECE551 Midterm Version 1
Name: ECE551 Midterm Version 1 NetID: There are 7 questions, with the point values as shown below. You have 75 minutes with a total of 75 points. Pace yourself accordingly. This exam must be individual
More informationC Syntax Arrays and Loops Math Strings Structures Pointers File I/O. Final Review CS Prof. Jonathan Ventura. Prof. Jonathan Ventura Final Review
CS 2060 Variables Variables are statically typed. Variables must be defined before they are used. You only specify the type name when you define the variable. int a, b, c; float d, e, f; char letter; //
More informationC Input/Output. Before we discuss I/O in C, let's review how C++ I/O works. int i; double x;
C Input/Output Before we discuss I/O in C, let's review how C++ I/O works. int i; double x; cin >> i; cin >> x; cout
More informationEECS2031. Modifiers. Data Types. Lecture 2 Data types. signed (unsigned) int long int long long int int may be omitted sizeof()
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 information211: Computer Architecture Summer 2016
211: Computer Architecture Summer 2016 Liu Liu Topic: C Programming Data Representation I/O: - (example) cprintf.c Memory: - memory address - stack / heap / constant space - basic data layout Pointer:
More informationCOP 3223 Introduction to Programming with C - Study Union - Fall 2017
COP 3223 Introduction to Programming with C - Study Union - Fall 2017 Chris Marsh and Matthew Villegas Contents 1 Code Tracing 2 2 Pass by Value Functions 4 3 Statically Allocated Arrays 5 3.1 One Dimensional.................................
More informationCh 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 informationMemory Layout, File I/O. Bryce Boe 2013/06/27 CS24, Summer 2013 C
Memory Layout, File I/O Bryce Boe 2013/06/27 CS24, Summer 2013 C Outline Review HW1 (+command line arguments) Memory Layout File I/O HW1 REVIEW HW1 Common Problems Taking input from stdin (via scanf) Performing
More informationComputer Programming Unit 3
POINTERS INTRODUCTION Pointers are important in c-language. Some tasks are performed more easily with pointers such as dynamic memory allocation, cannot be performed without using pointers. So it s very
More informationMemory Management. CSC215 Lecture
Memory Management CSC215 Lecture Outline Static vs Dynamic Allocation Dynamic allocation functions malloc, realloc, calloc, free Implementation Common errors Static Allocation Allocation of memory at compile-time
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 informationo Code, executable, and process o Main memory vs. virtual memory
Goals for Today s Lecture Memory Allocation Prof. David August COS 217 Behind the scenes of running a program o Code, executable, and process o Main memory vs. virtual memory Memory layout for UNIX processes,
More informationChapter 2 (Dynamic variable (i.e. pointer), Static variable)
Chapter 2 (Dynamic variable (i.e. pointer), Static variable) August_04 A2. Identify and explain the error in the program below. [4] #include int *pptr; void fun1() { int num; num=25; pptr= #
More informationFile 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 informationLecture 7: Files. opening/closing files reading/writing strings reading/writing numbers (conversion to ASCII) command line arguments
Lecture 7: Files opening/closing files reading/writing strings reading/writing numbers (conversion to ASCII) command line arguments Lecture 5: Files, I/O 0IGXYVI*MPIW 0 opening/closing files reading/writing
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 informationLecture 05 Pointers ctd..
Lecture 05 Pointers ctd.. Note: some notes here are the same as ones in lecture 04 1 Introduction A pointer is an address in the memory. One of the unique advantages of using C is that it provides direct
More informationProcedural Programming
Exercise 5 (SS 2016) 28.06.2016 What will I learn in the 5. exercise Strings (and a little bit about pointer) String functions in strings.h Files Exercise(s) 1 Home exercise 4 (3 points) Write a program
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 informationProgram Design (II): Quiz2 May 18, 2009 Part1. True/False Questions (30pts) Part2. Multiple Choice Questions (40pts)
Class: No. Name: Part1. True/False Questions (30pts) 1. Function fscanf cannot be used to read data from the standard input. ANS: False. Function fscanf can be used to read from the standard input by including
More informationPointers, Arrays, and Strings. CS449 Spring 2016
Pointers, Arrays, and Strings CS449 Spring 2016 Pointers Pointers are important. Pointers are fun! Pointers Every variable in your program has a memory location. This location can be accessed using & operator.
More informationProgramming & 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