Memory Management and
|
|
- Allan Hardy
- 5 years ago
- Views:
Transcription
1 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
2 Dynamic memory allocation l malloc Syntax: #include <stdlib.h>!!!!void* malloc( size_t n );! size_t è unsigned integer Ø scanf("iu", &n); printf("%iu", n); // for Windows! Ø scanf("zu", &n); printf("%zu", n); // for UNIX! 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 2
3 Dynamic memory allocation 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(). 3
4 Dynamic memory allocation l Example: // 10 characters:! char *pc = (char *)malloc( sizeof(char) * 10);! // 10 integers:! int *pi = (int *)malloc( sizeof(int) * 10);! // 10 doubles:! double *pd = (double *)malloc( sizeof(double) * 10);!! if( pc!= NULL && pi!= NULL && pd!= NULL){! 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]);! }!! // Deallocation! free(pc);! free(pi);! free(pd);! 4
5 Dynamic memory allocation l free a NULL pointer int *p; free(p); p = NULL;! free(p);!// Non-NULL!!// Runtime error!!!// OK! 5
6 Dynamic memory allocation l calloc Syntax:!#include <stdlib.h>!!!!void* calloc (size_t n, size_t size );! calloc() returns a pointer to a chunk of memory of n*size bytes with elements initialized t zero, or NULL if there is an error. The returned pointer must be typecast 6
7 Dynamic memory allocation int n = 1024 * 1024 * 128 * sizeof(char); // 128M chars! double rtime;! clock_t clk0, clk1;!! // The time of malloc and initialization is proportional to n! clk0 = clock();! char *pc = (char *)malloc(n);! 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);!! free(pc);!! // The time of calloc is constant if hardware supports calloc! clk0 = clock();! pc = (char *)calloc(n, sizeof(char));! clk1 = clock();! rtime = (double)(clk1 - clk0) / (double)clocks_per_sec;! printf("calloc time: %f\n", rtime);!! free(pc);! 7
8 Dynamic memory allocation l realloc Syntax:!#include <stdlib.h>!!!!void * realloc( void * ptr, size_t n);! ptr: Pointer to a memory block previously allocated with malloc, calloc or realloc, or a null pointer (to allocate a new block). n: New size for the memory block, in bytes. Ø If n is zero, the return value depends on the particular library implementation, but the returned pointer shall not be used. A pointer to the reallocated memory block, which may be either the same as ptr or a new location. The returned pointer must be typecast If the function failed to allocate the requested block of memory, a null pointer is returned, and the memory block pointed to by argument ptr is not deallocated (it is still valid, and with its contents unchanged). 8
9 Dynamic memory allocation int i = 0, n = 0, x = 0, *p = NULL;! while(scanf("%d", &x)!= EOF){! ++n;! p = (int *)realloc(p, n * sizeof(int));! p[n-1] = x;! for(i=0; i<n; ++i)! printf("%d, ", p[i]);! printf("\n");!! }! free(p);! 9
10 Dynamic memory allocation l Memory leaks and dangling Normal allocation Pointer Memory Memory leaks Memory dangling Pointer Memory Pointer Memory 10
11 Dynamic memory allocation l Memory Leaks There is no any pointer to point an allocated memory space Take look the following example: Ø 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. 11
12 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!! pc pi Memory free 12
13 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, *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]);! free(p); 13
14 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. 14
15 Dynamic memory allocation l Memory Manipulation Functions memcpy, memory copy: char s1[] = "Hello! My friend!"; // Why do we use char[]?! const char *s2 = "Hi! Guys."; // Why do we 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 15
16 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);!! // ! 16
17 Dynamic memory allocation l Memory Manipulation Functions memcmp, memory compare: #include <memory.h> or #include <string.h>! int memcmp(const void *p1, const void *p2, size_t n );! Ø p1 and p2: the pointers of memory Ø n: the number of byte to compare Ø Return Value: relationship of first n bytes of buf1 and buf2 Ø return (p1[i] p2[i]), if (p1[i] p2[i]!= 0 or i == n-1), i = 0, 1,, n-1 < 0: p1 less than p2 0: p1 identical to p2 > 0: p1 greater than p2 char first[] = " ";! char second[] = " ";! printf("%d\n", memcmp( first, second, 19 ) ); // 0! printf("%d\n", memcmp( first, second, 20 ) ); // <0! printf("%d\n", memcmp( first + 2, second, 18 ) ); // >0! 17
18 Dynamic memory allocation l Case study: recording the weights and heights int main(void)! {! const size_t n = 5;! float A[n][2] = {0};! int i=0;! for(i=0; i<n; ++i){ // Data input.! printf("w H: ");! scanf("%f %f", &A[i][0], &A[i][1]);! }! qsort(a, n, sizeof(float) * 2, cmpw );!// By weight! for(i=0; i<n; ++i) // Data input.! printf("(%f, %f) ", A[i][0], A[i][1]);! printf("\n");! qsort(a, n, sizeof(float) * 2, cmph ); // By height! for(i=0; i<n; ++i) // Data input.! printf("(%f, %f) ", A[i][0], A[i][1]);! printf("\n");! }!! 18
19 Dynamic memory allocation l Case study: recording the weights and heights int cmpw( const void* p1, const void*p2){! float *pf1 = (float*)p1;! float *pf2 = (float*)p2;! return pf1[0] - pf2[0];! }!! int cmph( const void* p1, const void*p2){! float *pf1 = (float*)p1;! float *pf2 = (float*)p2;! return pf1[1] - pf2[1];! }!! 19
20 Dynamic memory allocation l Case study: recording the weights and heights (dynamic memory alloc) size_t n = 0;! printf("n="); scanf("%iu", &n); getchar(); // n=?! // Memory allocation, watch the array pointer declaration! float (*A)[2] = (float (*)[2])calloc(n, sizeof(float)*2);! int i=0;! for(i=0; i<n; ++i){! printf("w H: ");! scanf("%f %f", &A[i][0], &A[i][1]);! }! qsort(a, n, sizeof(float) * 2, cmpw ); // By weight! for(i=0; i<n; ++i)! printf("(%f, %f) ", A[i][0], A[i][1]); // By height! printf("\n");! qsort(a, n, sizeof(float) * 2, cmph );! for(i=0; i<n; ++i)! printf("(%f, %f) ", A[i][0], A[i][1]);! printf("\n");! free(a);!! 20
21 Struct l struct To design a custom data type To group multiple relevant data Heterogeneous array struct Student{! char name[8];! float w, h;! };! Student x = {0};! printf("name:%s, w:%f, h:%f\n", x.name, x.w, x.h);!! Student y = {"James", 75.2f, 175.6f};! printf("name:%s, w:%f, h:%f\n", y.name, y.w, y.h);! Student z = y;! printf("name:%s, w:%f, h:%f\n", y.name, y.w, y.h);! scanf("%s %f %f", z.name, &z.w, &z.h);! getchar();! printf("name:%s, w:%f, h:%f\n", z.name, z.w, z.h); 21
22 Struct l member selection operator x.m x is the object name m is the member name p->m p is a pointer points an object m is the member name member = field Student x;!!! x.w = 65.0f; x.h = 178.5f;!!! Student * px = &x;! px->w = 75.4f, px->h = 190.0f; 22
23 Struct l Passing a struct object to a function by its address DO NOT by value! void InputStudent(Student* px){! scanf("%s %f %f", px->name, &px->w, &px->h);! }!! void PrintStudent (const struct Student* px){! printf("name:%s, w:%f, h:%f\n", px->name, px->w, px->h); }! 23
24 Dynamic memory allocation l Case study: recording the weights and heights (struct) int cmpw( const void* p1, const void*p2){ /*??? */ }! int cmph( const void* p1, const void*p2) {/*??? */}! int main(void){! size_t n = 0, i = 0;! printf("n="); scanf("%iu", &n); getchar(); // n=?! // Memory allocation, watch the array pointer declaration! Student *A = //???! // ---??? ---!! // ! printf("sorted by weight:\n");! // qsort(???);! for(i=0; i<n; ++i)! // PrintStudent??;! printf("sorted by hight:\n");! // qsort(???);! for(i=0; i<n; ++i)! // PrintStudent??;! }!! 24
25 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 blocks of elements may not be adjacent
26 Linked Lists l Linked List struct Node{! int data;! Node *next;! };! data next void ShowNode(const Node* p){! printf("%d\n", p->data);! }! // Default argument function Only in C++! // The defaults of data and pnext are 0 and NULL respectively.! Node* NewNode(int data = 0, Node *pnext = NULL){! Node x = {data, pnext};! Node *p = (Node *)malloc(sizeof(node));! *p = x;! return p;! }! 26
27 Linked Lists l Linked List // Creation! Node *phead = NULL;! for( int i=5; i>=0; --i)! phead = NewNode(i, phead);!! // Output! Node *p = phead;! while(p!= NULL) {! ShowNode(p);! p = p->next;! }! // deletion all! p = phead;! while(p!= NULL) {! Node *ptmp = p;! }! p = p->next;! free(ptmp); phead p !// Release each item! 27
28 Linked Lists l Linked List // Output! void ShowList(const Node *p){! while(p!= NULL) {! ShowNode(p);! p = p->next;! }! }!! // deletion all! Node* DelList(Node *p){! while(p!= NULL) {! Node *ptmp = p;! p = p->next;! free(ptmp);!! }! return NULL;! }! // Creation! Node *phead = NULL;! for( int i=5; i>=0; --i)! phead = NewNode(i, phead);!! ShowList(pHead);!! phead = DelList(pHead);! 28
29 Linked Lists l Linked List // Front Insertion! Node * PushFront( Node* p0, Node *pnew){! if(p0!= NULL)! pnew->next = p0;! return pnew;! }!!! int main(){! Node *phead = NULL;! }! phead pnew for( int i=5; i>=0; --i)! phead = FrontIns( phead, NewNode(i, NULL));! ShowList(pHead);! phead = DelList(pHead);! p0 29
30 Linked Lists l Linked List // Front erasing! Node * PopFront( Node* phead){! if(phead!= NULL){! Node *ptmp = phead;! phead = phead->next;! free(ptmp);! }! return phead;! phead }! ptmp! // deletion all! Node* DelList(Node *p){! while( (p = PopFront(p))!= NULL );! return p;! }! 30
31 Linked Lists l Exercises Back insertion Node * PushBack( Node* phead, Node *pnew);! phead: The pointer points the first node of list pnew: The pointer points the new node; The return is the header of list Back erasing Node * PopBack( Node* phead);! phead: The pointer points the first node of list The return is the header of list. If the list is empty, the return is NULL. 31
32 Linked Lists l Exercises Search Node * Search( Node* phead, int key);! phead: The pointer points the first node of list key: The search key The return is the pointer of the searched node if the node exists in the list. Otherwise the return is NULL remove the specified node Node * remove( Node* phead, int key);! phead: The pointer points the first node of list key: The target key The return is the header of list. If the list is empty, the return is NULL. 32
33 File System in OS l Microsoft Windows Filename DriveID : /DirctoryName/MainFileName.ExtensionName EX: Ø C:/test.txt Ø D:/MyDoc/Reports/ ppt Directories or Folders Storage Devices Files Files Directories or Folders Files 33
34 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 34
35 File System in OS l Microsoft Windows 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 35
36 File System in OS l Microsoft Windows FAT32 (File Allocation Table 32-bit) Max. file size: 4 GB Max. length of MainFileName: 255 (in Windows), 8+3(DOS) Protection: Read-Only, Hidden and System exfat (Extended File Allocation Table) Max. file size: 64 ZebiB = 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) 36
37 File System in OS l UNIX family UNIX, FreeBSD, Linux, MAC OS X Tree structure file system Each node is either file or directory root etc usr volumes DVD USB-Disk data1 data2 37
38 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);! }! 38
39 File I/O in C l Stream I/O 1. Open file FILE * file;! file = fopen( "C:/MyDoc/data.txt", "r" );! // 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);! 39
40 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. 40
41 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. 41
42 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 42
43 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 43
44 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"); // try "rb"! int c = 0;! while( (c = fgetc(pf))!= EOF)! printf("%02x ", c);! printf("\n");! fclose(pf);! }! 44
45 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
46 File I/O in C l printf & scanf for file int fprintf(file *pfile, const char *format [, arg]...);! int fscanf(file *pfile, const char *format [, arg]...);! #include <stdio.h>! int main(){! FILE *pf = fopen("a.txt", "wb");! for(int i=0; i<10; ++i)!! fprintf(pf, "LINE[%d]\n", i);! fclose(pf);!! pf = fopen("a.txt", "rb");! char A[255] = {0};! while(fscanf(pf, "%s", A)!= EOF)! printf("%s\n", A);! fclose(pf);! }! 46
47 Exercise: PackBits l PackBits A data compression algorithm Invented by Apple Fast, simple and lossless It's suitable for image files, but unsuitable for text files Run-length encoding (RLE) 將一連串相同重複的 byte 改以兩個 byte 來表示, 第一個 byte 代表重複次數, 後第二個 byte 是資料 EX: Ø 0A 0A 0A 0A 0A è 05 0A TIFF and TGA image file use PackBits to compress the image data 47
48 Exercise: PackBits l Algorithm int n =0; while( n < MaxSize ) Read the next source byte into B. if (0 B 127){ read the next B+1 bytes. n += B + 1; } else if (-127 B -1){ read the next byte -B+1 times. n += (-B + 1) } } EX AA AA AA A AA AA AA AA A 22 AA AA AA AA AA AA AA AA AA AA è FE AA A FD AA A 22 F7 AA 48
49 Exercise: PackBits l Requirement: Using PackBits to compress a BMP or TIF file And send the compressed file to other classmate. Uncompressing the compressed file 49
Memory Management and
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 Dynamic memory allocation l malloc Syntax:
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 informationIntroduction 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 informationCSCI 2212: Intermediate Programming / C Storage Class and Dynamic Allocation
... 1/30 CSCI 2212: Intermediate Programming / C Storage Class and Dynamic Allocation Alice E. Fischer October 23, 2015 ... 2/30 Outline Storage Class Dynamic Allocation in C Dynamic Allocation in C++
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 informationDynamic Allocation in C
Dynamic Allocation in C C Pointers and Arrays 1 The previous examples involved only targets that were declared as local variables. For serious development, we must also be able to create variables dynamically,
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 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 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 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 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 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 informationSlide 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 informationCourse organization. Course introduction ( Week 1)
Course organization Course introduction ( Week 1) Code editor: Emacs Part I: Introduction to C programming language (Week 2-9) Chapter 1: Overall Introduction (Week 1-3) Chapter 2: Types, operators and
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 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 informationFundamental of Programming (C)
Borrowed from lecturer notes by Omid Jafarinezhad Fundamental of Programming (C) Lecturer: Vahid Khodabakhshi Lecture 9 Pointer Department of Computer Engineering 1/46 Outline Defining and using Pointers
More informationUNIT IV-2. The I/O library functions can be classified into two broad categories:
UNIT IV-2 6.0 INTRODUCTION Reading, processing and writing of data are the three essential functions of a computer program. Most programs take some data as input and display the processed data, often known
More informationLecture 9: File Processing. Quazi Rahman
60-141 Lecture 9: File Processing Quazi Rahman 1 Outlines Files Data Hierarchy File Operations Types of File Accessing Files 2 FILES Storage of data in variables, arrays or in any other data structures,
More 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 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 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 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 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 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 informationArrays and Pointers. CSE 2031 Fall November 11, 2013
Arrays and Pointers CSE 2031 Fall 2013 November 11, 2013 1 Arrays l Grouping of data of the same type. l Loops commonly used for manipulation. l Programmers set array sizes explicitly. 2 Arrays: Example
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 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 informationAPS105. Malloc and 2D Arrays. Textbook Chapters 6.4, Datatype Size
APS105 Malloc and 2D Arrays Textbook Chapters 6.4, 10.2 Datatype Size Datatypes have varying size: char: 1B int: 4B double: 8B int sizeof(): a builtin function that returns size of a type int x =
More informationCP2 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 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 informationFundamentals 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 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 informationStandard I/O in C, Computer System and programming in C
Standard I/O in C, Contents 1. Preface/Introduction 2. Standardization and Implementation 3. File I/O 4. Standard I/O Library 5. Files and Directories 6. System Data Files and Information 7. Environment
More informationArrays and Pointers. Arrays. Arrays: Example. Arrays: Definition and Access. Arrays Stored in Memory. Initialization. EECS 2031 Fall 2014.
Arrays Arrays and Pointers l Grouping of data of the same type. l Loops commonly used for manipulation. l Programmers set array sizes explicitly. EECS 2031 Fall 2014 November 11, 2013 1 2 Arrays: Example
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 informationM.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 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 informationfopen() fclose() fgetc() fputc() fread() fwrite()
The ability to read data from and write data to files is the primary means of storing persistent data, data that does not disappear when your program stops running. The abstraction of files that C provides
More 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 informationStudent Number: Instructor: Reid Section: L5101 (6:10-7:00pm)
Final Test Duration 50 minutes Aids allowed: none Last Name: Student Number: First Name: Instructor: Reid Section: L5101 (6:10-7:00pm) Do not turn this page until you have received the signal to start.
More informationProgramming Language B
Programming Language B Takako Nemoto (JAIST) 7 January Takako Nemoto (JAIST) 7 January 1 / 13 Usage of pointers #include int sato = 178; int sanaka = 175; int masaki = 179; int *isako, *hiroko;
More informationCS61, Fall 2012 Section 2 Notes
CS61, Fall 2012 Section 2 Notes (Week of 9/24-9/28) 0. Get source code for section [optional] 1: Variable Duration 2: Memory Errors Common Errors with memory and pointers Valgrind + GDB Common Memory Errors
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 informationLecture 5: Multidimensional Arrays. Wednesday, 11 February 2009
Lecture 5: Multidimensional Arrays CS209 : Algorithms and Scientific Computing Wednesday, 11 February 2009 CS209 Lecture 5: Multidimensional Arrays 1/20 In today lecture... 1 Let s recall... 2 Multidimensional
More informationContent. In this chapter, you will learn:
ARRAYS & HEAP Content In this chapter, you will learn: To introduce the array data structure To understand the use of arrays To understand how to define an array, initialize an array and refer to individual
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 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 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 informationTHE FUNDAMENTAL DATA TYPES
THE FUNDAMENTAL DATA TYPES Declarations, Expressions, and Assignments Variables and constants are the objects that a prog. manipulates. All variables must be declared before they can be used. #include
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 informationSystem 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 informationLectures 5-6: Introduction to C
Lectures 5-6: Introduction to C Motivation: C is both a high and a low-level language Very useful for systems programming Faster than Java This intro assumes knowledge of Java Focus is on differences Most
More informationComputer 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 informationEL2310 Scientific Programming
Lecture 11: Memory, Files and Bitoperations (yaseminb@kth.se) Overview Overview Lecture 11: Memory, Files and Bit operations Main function; reading and writing Bitwise Operations Lecture 11: Memory, Files
More informationDynamic Allocation in C
Dynamic Allocation in C 1 The previous examples involved only targets that were declared as local variables. For serious development, we must also be able to create variables dynamically, as the program
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 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 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 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 informationLectures 5-6: Introduction to C
Lectures 5-6: Introduction to C Motivation: C is both a high and a low-level language Very useful for systems programming Faster than Java This intro assumes knowledge of Java Focus is on differences Most
More informationFile and Console I/O. CS449 Spring 2016
File and Console I/O CS449 Spring 2016 What is a Unix(or Linux) File? File: a resource for storing information [sic] based on some kind of durable storage (Wikipedia) Wider sense: In Unix, everything is
More informationGoals of this Lecture
I/O Management 1 Goals of this Lecture Help you to learn about: The Unix stream concept Standard C I/O functions Unix system-level functions for I/O How the standard C I/O functions use the Unix system-level
More 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 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 informationI/O Management! Goals of this Lecture!
I/O Management! 1 Goals of this Lecture! Help you to learn about:" The Unix stream concept" Standard C I/O functions" Unix system-level functions for I/O" How the standard C I/O functions use the Unix
More informationArrays. An array is a collection of several elements of the same type. An array variable is declared as array name[size]
(November 10, 2009 2.1 ) Arrays An array is a collection of several elements of the same type. An array variable is declared as type array name[size] I The elements are numbered as 0, 1, 2... size-1 I
More informationI/O Management! Goals of this Lecture!
I/O Management! 1 Goals of this Lecture! Help you to learn about:" The Unix stream concept" Standard C I/O functions" Unix system-level functions for I/O" How the standard C I/O functions use the Unix
More 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 informationFile I/O. Last updated 10/30/18
Last updated 10/30/18 Input/Output Streams Information flow between entities is done with streams Keyboard Text input stream data stdin Data Text output stream Monitor stdout stderr printf formats data
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 informationMODULE 5: Pointers, Preprocessor Directives and Data Structures
MODULE 5: Pointers, Preprocessor Directives and Data Structures 1. What is pointer? Explain with an example program. Solution: Pointer is a variable which contains the address of another variable. Two
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 informationCOP 3223 Introduction to Programming with C - Study Union - Spring 2018
COP 3223 Introduction to Programming with C - Study Union - Spring 2018 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 information