Chapter 12. Text and Binary File Processing. Instructor: Öğr. Gör. Okan Vardarlı. Copyright 2004 Pearson Addison-Wesley. All rights reserved.
|
|
- Hector Armstrong
- 6 years ago
- Views:
Transcription
1 Chapter 12 Text and Binary File Processing Instructor: Öğr. Gör. Okan Vardarlı Copyright 2004 Pearson Addison-Wesley. All rights reserved.
2 Objectives We will explore the use of standard input, standard output, and program-controlled text files. We will introduce binary files. We will compare the advantages and disadvantages of text and binary files. Copyright 2004 Pearson Addison-Wesley. All rights reserved. 12-2
3 Why Files? Large volume of input data Large volume of output data More permanent storage of data Transfer to other programs Multiple simultaneous input and/or output streams E.g.: Business Data: customer files, payroll files, Scientific Data: weather data, environmental data Image Data: web images, satellite images, medical images, Web Data: HTML, GIF, JPEG, PNG, XML, 12-3
4 Files in C In C, each file is simply a sequential stream of bytes. C imposes no structure on a file. Thus, notions such as a record of a file do not exist as part of the C language. There are two formats for files: Text files: a collection of characters saved in secondary storage (e.g. on a disk). They contain variable length records They must be accessed sequentially, processing all records from the start of file to access a particular record Binary files: binary numbers that are the computer s internal representation of each file component. For example 49 is in a binary file, but it is 4 and 9 in a text file. They contain fixed length records They can be accessed directly (directly accessing the record that is required) Binary files are appropriate for online transaction processing systems, e.g. airline reservation, order processing, banking systems etc. 12-4
5 Files vs. File variables A file variable is a data structure in the C program which represents the file Temporary: exists only when program runs There is a struct called FILE in <stdio.h> Details of the struct are private to the standard C I/O library routines. Information like definitions of useful #define constants such as EOF for End of File are kept here. 12-5
6 Files and Streams C views each file simply as a sequential stream of bytes (Fig. 11.1). Each file ends either with an end-of-file marker or at a specific byte number recorded in a system-maintained, administrative data structure. When a file is opened, a stream is associated with it. Three files and their associated streams are automatically opened when program execution begins the standard input, the standard output and the standard error. Streams provide communication channels between files and programs by Pearson Education, Inc. All Rights Reserved.(Deitel & Deitel 11.2) 12-6
7 Files and Streams (Cont.) The standard library provides many functions for reading data from files and for writing data to files. Function fgetc, like getchar, reads one character from a file. Function fgetc receives as an argument a FILE pointer for the file from which a character will be read. The call fgetc( stdin ) reads one character from stdin the standard input. This call is equivalent to the call getchar(). Function fputc, like putchar, writes one character to a file. Function fputc receives as arguments a character to be written and a pointer for the file to which the character will be written by Pearson Education, Inc. All Rights Reserved.(Deitel & Deitel 11.2) 12-7
8 Files and Streams (Cont.) The function call fputc( 'a', stdout ) writes the character 'a' to stdout the standard output. This call is equivalent to putchar( 'a' ). Several other functions used to read data from standard input and write data to standard output have similarly named fileprocessing functions. The fgets and fputs functions, for example, can be used to read a line from a file and write a line to a file, respectively. In the next several sections, we introduce the file-processing equivalents of functions scanf and printf fscanf and fprintf by Pearson Education, Inc. All Rights Reserved.(Deitel & Deitel 11.2) 12-8
9 Opening a file A file must first be opened properly before it can be accessed for reading or writing. When a file is opened, a stream is associated with the file. Successfully opening a file returns a pointer to (i.e., the address of) a file structure, which contains a file descriptor and a file control block. 12-9
10 Opening a file A file must first be opened properly before it can be accessed for reading or writing. When a file is opened, a stream is associated with the file. Successfully opening a file returns a pointer to (i.e., the address of) a file structure, which contains a file descriptor and a file control block. File is placed in the same folder with the program unless specified. Such as "C:\\test1.txt" 12-10
11 Opening a file The statement: FILE *fptr1, *fptr2 ; declares that fptr1 and fptr2 are pointer variables of type FILE. They will be assigned the address of a file descriptor, that is, an area of memory that will be associated with an input or output stream. Whenever you are to read from or write to the file, you must first open the file and assign the address of its file descriptor (or structure) to the file pointer variable. Pointer arithmetic can NOT be applied to the file pointers
12 Opening a file FILE *fopen(const char *path, const char *mode); The fopen() function opens the file whose name is the string pointed to by path and associates a stream with it. The argument mode points to a string beginning with one of the following sequences (see next slide). In the example below, "r" stands for read only. Let s open an existing file named mydata.txt FILE *fptr1 ; fptr1 = fopen ( "mydata.txt", "r") ; Copyright 2004 Pearson Addison-Wesley. All rights reserved
13 Basic File Opening Modes: Mode Meaning fopen Returns if FILE- Exists Not Exists r Reading NULL w Writing Over write on Existing a Append r+ w+ a+ Reading + Writing Reading + Writing Reading + Appending New data is written at the beginning overwriting existing data Open a text file for update (reading and writing), first truncating the file to zero length New data is appended at the end of file Create New File Create New File Create New File Create New File Create New File 12-13
14 File opening modes by Pearson Education, Inc. All Rights Reserved.(Deitel & Deitel 11.5) 12-14
15 Testing for Successful Open If the file was not able to be opened, then the value returned by the fopen routine is NULL. For example, let's assume that the file mydata does not exist. Then: FILE *fptr1 ; fptr1 = fopen ( "mydata.txt", "r") ; if (fptr1 == NULL) { printf ("File 'mydata' did not open.\n") ; 12-15
16 Common Programming Errors by Pearson Education, Inc. All Rights Reserved.(Deitel & Deitel 11.5) 12-16
17 Reading formatted data from a file int fscanf ( FILE * stream, const char * format,... ); INPUT: Format string is analogous to scanf format string %d for integer, %c for character etc. And must have an argument for each format specifier. OUTPUT: On success, fscanf returns the number of items read; can be 0 if the pattern doesn't match. On failure, returns EOF
18 Reading From Files In the following segment of C language code: int a, b ; FILE *fptr1, *fptr2 ; fptr1 = fopen ( "mydata.txt", "r" ) ; fscanf ( fptr1, "%d%d", &a, &b) ; the fscanf function would read values from the file "pointed" to by fptr1 and assign those values to a and b. In the segment of code shown the file mydata is opened and the file pointer fptr1 is assigned to the open file. Then the fscanf function scans for two integers from this file and assigns the values read to the variables a and b
19 End of File (EOF) Status EOF: a special status value Returned by scanf and fscanf when end of data is reached defined in stdio.h #define EOF (some negative value) I/O library routines use EOF in various ways to signal end of file. Your programs can check for EOF EOF is a status, not an input value! 12-19
20 End of File The end-of-file indicator informs the program when there are no more data (no more bytes) to be processed. There are a number of ways to test for the end-of-file condition. One is to use the feof function which returns a true or false condition: fscanf (fptr1, "%d", &var) ; if ( feof (fptr1) ) { printf ("End-of-file encountered.\n ); 12-20
21 End of File There are a number of ways to test for the end-of-file condition. Another way is to use the value returned by the fscanf function: int istatus ; istatus = fscanf (fptr1, "%d", &var) ; if ( istatus == EOF ) { printf ("End-of-file encountered.\n ) ; 12-21
22 Going to the beginning of a file void rewind ( FILE * stream ); EFFECT Moves file pointer to beginning of file Resets end-of-file indicator Reset error indicator Forgets any virtual characters from ungetc E.g. rewind(fptr1); 12-22
23 Writing a formatted string to a file int fprintf ( FILE * stream, const char * format,... ) INPUT The format string is same as for printf Must have an argument for each specifier in the format OUTPUT / EFFECT On success, returns the number of character written On failure, returns a negative number 12-23
24 Writing a formatted string to a file Likewise in a similar way, in the following segment of C language code: int a = 5, b = 20 ; FILE *fptr2 ; fptr2 = fopen ( "results.txt", "w" ) ; fprintf ( fptr2, "%d %d\n", a, b ) ; the fprintf functions would write the values stored in a and b to the file "pointed" to by fptr
25 Closing Files The statements: fclose ( fptr1 ) ; fclose ( fptr2 ) ; will close the files and release the file descriptor space and I/O buffer memory
26 Reading and Writing Files #include <stdio.h> int main ( ) { FILE *outfile, *infile ; int b = 5, f ; float a = 13.72, c = 6.68, e, g ; outfile = fopen ("testdata.txt", "w") ; if (outfile == NULL) printf ("File 'testdata.txt' cannot be opened.\n"); else fprintf (outfile, "%6.2f%2d%5.2f", a, b, c) ; fclose (outfile) ; 12-26
27 Reading and Writing Files infile = fopen ("testdata.txt", "r") ; if (infile == NULL) printf ("File 'testdata.txt' cannot be opened.\n"); else{ fscanf (infile,"%f %d %f", &e, &f, &g) ; printf (" \n"); printf ("%6.2f,%2d,%5.2f\n", e, f, g) ; fclose (outfile) ; ; return 0; , 5,
28 //Reading from a file character by character #include <stdio.h> int main ( ) { FILE *infile ; char c; infile = fopen ("testdata.txt", "r") ; if (infile == NULL) printf ("File 'testdata.txt' cannot be opened.\n"); else{ printf (" \n"); c=getc(infile); while (c!= EOF) { putchar(c); //Print character to the screen c=getc(infile); fclose (infile) ; return 0; 12-28
29 //Appending data to an existing file then list it to the screen #include <stdio.h> int main ( ) { FILE *infile ; char c; infile = fopen ("testdata.txt", "a") ;//Open file for appending if (infile == NULL) printf ("File 'testdata.txt' cannot be opened.\n"); else fprintf(infile,"%c%s and a number:%d",'\n',"another line",3); fclose (infile) ; infile = fopen ("testdata.txt", "r") ;//Open file for reading if (infile == NULL) printf ("File 'testdata.txt' cannot be opened.\n"); else{ printf (" \n"); do{ if ((c = fgetc(infile))!= EOF) putchar(c); //Print character to the screen else break; while (1); fclose (infile) ; printf("\n"); return 0; 12-29
30 //Overwriting existing data from the beginning of the file #include <stdio.h> int main ( ) { FILE *infile ; char c; infile = fopen ("testdata.txt", "w+") ; if (infile == NULL) printf ("File 'testdata.txt' cannot be opened.\n"); else fprintf(infile,"here we go"); fclose (infile) ; infile = fopen ("testdata.txt", "r") ; if (infile == NULL) printf ("File 'testdata.txt' cannot be opened.\n"); else{ printf (" \n"); do { c=getc(infile); if (!feof(infile)) putchar(c); //Print character to the screen while (!feof(infile)); fclose (infile) ; printf("\n"); return 0; Previous file started with " 13.72" Now data at the beginning is overwritten
31 //Writing to and reading from a file #include <stdio.h> int main () { FILE *outfile, *infile ; int b = 5, f ; float a = 13.72, c = 6.68, e, g ; char line[80]; char *status; outfile = fopen ("testdata.txt", "w") ; if (outfile == NULL) printf ("File 'testdata.txt' cannot be opened.\n"); else{ fprintf (outfile, "%6.2f%2d%5.2f", a, b, c) ; fprintf (outfile, "%6.2f%2d%5.2f", a+1, b+1, c+1) ; fclose (outfile) ; infile = fopen("testdata.txt","r"); if (infile == NULL) printf ("File 'testdata.txt' cannot be opened.\n"); else{ printf (" \n"); fscanf (infile,"%f %d %f", &e, &f, &g) ; printf ("%6.2f%2d%5.2f\n", e, f, g) ; fscanf (infile,"%f %d %f", &e, &f, &g) ; printf ("%6.2f%2d%5.2f\n", e, f, g) ; fclose(infile); printf("\nlet's try to read full line:\n"); infile = fopen("testdata.txt","r"); if (infile == NULL) printf ("File 'testdata.txt' cannot be opened.\n"); else{ printf (" \n"); do{ status=fgets(line,80,infile); if (status!= NULL) printf("%s\n",line); while (status!= NULL); //Not EOF yet fclose(infile); return 0; 12-31
32 //Writing to and reading from a file #include <stdio.h> #include <string.h> int main(){ FILE *fp; char sentence[25]; int i; //Ceate a new file fp = fopen("tenlines.txt","w"); if (fp == NULL) printf ("File cannot be opened.\n"); else{ strcpy(sentence,"some thing."); for (i = 1;i <= 10;i++) fprintf(fp,"line#:%d %s\n",i,sentence); fclose(fp); printf("file is created successfully.\n"); fp = fopen("tenlines.txt","r"); //Let's read from the file if (fp == NULL) printf (" File cannot be opened.\n"); else{ for (i = 1;i <= 10;i++) { fgets(sentence,25,fp); printf("%s",sentence); fclose(fp); printf("\nlet's try a better way to read.\n"); fp = fopen("tenlines.txt","r"); if (fp == NULL) printf ("File 'TenLines.txt' cannot be opened.\n"); else{ int c; do { c = fgets(sentence,25,fp); if (c!= NULL) printf("%s",sentence); while (c!= NULL); //Not EOF yet fclose(fp); return 0; 12-32
33 Copying a file //Create a file then make a backup copy of it #include <stdio.h> int main ( ) { FILE *file1,*file2 ; char c; file1 = fopen ("test1.txt", "w") ; if (file1 == NULL) printf ("File 'test1.txt' cannot be opened.\n"); else fprintf (file1, "A few word.") ; fclose (file1) ; printf("content of test1.txt:\n"); file1 = fopen ("test1.txt", "r") ; if (file1 == NULL) printf ("File 'test1.txt' cannot be opened.\n"); else for(c=getc(file1);!feof(file1);c=getc(file1)) putc(c,stdout); printf("\n"); rewind(file1); //Move file pointer to the beginning file2 = fopen ("test2.txt", "w") ;//Backup file is openning if (file2 == NULL) printf ("File 'test2.txt' cannot be opened.\n"); else for(c=getc(file1);c!=eof;c=getc(file1)) putc(c,file2);//copy data from file1 to file2 fclose (file2); fclose (file1); printf("\ncontent of test2.txt:\n"); file2 = fopen ("test2.txt", "r") ; if (file1 == NULL) printf ("File 'test2.txt' cannot be opened.\n"); else do { c=getc(file2); if (!feof(file2)) putc(c,stdout); while (!feof(file2)); //Not EOF yet printf("\n"); fclose (file2); return 0; 12-33
34 What's wrong with this? #include <stdio.h> int main(){ FILE *fp = fopen ( "mydata.txt", "r" ) ; char state[3]; if (fp==null) printf("file mydata.txt cannot be opened"); else while(fscanf(fp,"%s", state)!= EOF) printf("i read: %s\n",state); return 0; 12-34
35 Buffer overruns Data is written to locations past the end of the buffer Hackers can exploit to execute arbitrary code User can always create an input longer than fixed size of buffer Don't use: scanf, fscanf, gets Use functions that limit the number of data read Use: fgets 12-35
36 Moving to a location fseek function Description The C library function sets the file position of the stream to the given offset. Declaration int fseek(file *stream, long int offset, int whence) Parameters stream This is the pointer to a FILE object that identifies the stream. offset This is the number of bytes to offset from whence. whence This is the position from where offset is added. It is specified by one of the following constants Origin constants: - SEEK_SET : seek from the beginning of the file (go byte) - SEEK_CUR: seek from the current file position (go byte) - SEEK_END: seek from the end of the file (go byte) Return Value This function returns zero if successful, or else it returns a non-zero value
37 Moving to a location #include <stdio.h> int main () { FILE * fp = fopen("myfile.txt", "w" ); fputs ( "This is an apple.", fp ); fseek ( fp, 9, SEEK_SET ); fputs ( " sam", fp ); fclose ( fp ); return(0); Open myfile.txt, you will see the content of it changed to: This is a sample 12-37
38 Where is the pointer? ftell function Description The C library function returns the current file position of the given stream. Declaration long int ftell(file *stream) Parameters stream This is the pointer to a FILE object that identifies the stream. Return Value This function returns the current value of the position indicator. If an error occurs, -1L is returned, and the global variable errno is set to a positive value
39 //Let s see how many bytes does file.txt have #include <stdio.h> int main () { FILE *fp; int len; fp = fopen("file.txt", "r"); if( fp == NULL ) { printf ("Error opening file"); return (-1); fseek(fp, 0, SEEK_END); len = ftell(fp); fclose(fp); printf("total size of file.txt = %d bytes\n", len); return(0); 12-39
40 Removing a file int remove ( const char * filename ) OUTPUT On success, returns 0 On failure, returns a non-zero value 12-40
41 Renaming a file int rename ( const char * oldname, const char * newname ) OUTPUT On success, returns 0 On failure, returns a non-zero value 12-41
42 Binary Files As we mentioned earlier, binary files containing binary numbers that are the computer s internal representation of each file component. For example 49 is in a binary file, but it is 4 and 9 in a text file. They contain fixed length records, usually arrays or structures They can be accessed directly (directly accessing the record that is required) Binary files are appropriate for online transaction processing systems, e.g. airline reservation, order processing, banking systems etc
43 In a Random Access File Data Data unformatted (stored as "raw bytes") in random access files All records of the same type have a fixed length Data not human readable
44 by Pearson Education, Inc. All Rights Reserved.(Deitel & Deitel 11.2)
45 11.5 Random-Access Files (Cont.) Fixed-length records enable data to be inserted in a random-access file without destroying other data in the file. Data stored previously can also be updated or deleted without rewriting the entire file by Pearson Education, Inc. All Rights Reserved.
46 Opening Binary Files Add b to the fopen mode string binaryp = fopen( nums.bin, wb ); wb : write binary rb : read binary ab : append binary 12-46
47 Binary I/O Functions There are following two functions, which can be used for binary input and output: fread and fwrite If you want to test while reading a binary file, either test right after you read a record with feof command or test numbers of items read to make sure end of file is not reached yet
48 Write to a file - fwrite function Description The C library function writes data from the array pointed to, by ptr to the given stream. Declaration size_t fwrite (const void * ptr, size_t size, size_t count, FILE * stream) Parameters ptr This is the pointer to the array of elements to be written. size This is the size in bytes of each element to be written. nmemb This is the number of elements, each one with a size of size bytes. stream This is the pointer to a FILE object that specifies an output stream. Return Value This function returns the total number of elements successfully returned as a size_t object, which is an integral data type. If this number differs from the nmemb parameter, it will show an error
49 Reading Binary Files - fread function Description The C library function reads data from the given stream into the array pointed to, by ptr. Declaration size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream) Parameters ptr This is the pointer to a block of memory with a minimum size of size*nmemb bytes. size This is the size in bytes of each element to be read. nmemb This is the number of elements, each one with a size of size bytes. stream This is the pointer to a FILE object that specifies an input stream. Return Value The total number of elements successfully read are returned as a size_t object, which is an integral data type. If this number differs from the nmemb parameter, then either an error had occurred or the End Of File was reached
50 Binary File I/O Writing binary files fwrite function E.g: fwrite(&i, sizeof(int), 1, binaryp); &i: the address of the first memory cell whose contents are copied to the file (here i is an integer variable). sizeof(int) : the number of bytes to copy to the file for one component. sizeof can be applied to both built-in and userdefined types. 1:the number of values to write to the binary file. binaryp:file pointer Reading binary files fread function E.g: fread(&i, sizeof(int), 1, binaryp); &i: the address of the first memory cell whose contents are copied from the file (here i is an integer variable). Other parameters are used similar way 12-50
51 //Creating a text file with fwrite function #include<stdio.h> int main () { FILE *fp; char str[] = "This is a test."; //Print the content of the file file.txt #include <stdio.h> int main () { FILE *fp; int c; fp = fopen( "file.bin", "wb" ); fwrite(str, sizeof(str), 1, fp ); fclose(fp); return(0); fp = fopen("file.bin","rb"); while(1) { c = fgetc(fp); if( feof(fp) ) { break ; printf("%c", c); fclose(fp); return(0); Note: You might see the content of this file since all data is in ASCII format
52 Searching Binary Files - fseek function Description The C library function int fseek(file *stream, long int offset, int whence) sets the file position of the stream to the given offset. Declaration int fseek(file *stream, long int offset, int whence) Parameters stream This is the pointer to a FILE object that identifies the stream. offset This is the number of bytes to offset from whence. whence This is the position from where offset is added. It is specified by one of the following constants Return Value This function returns zero if successful, or else it returns a non-zero value
53 //Creating a binary file with a structure //Saving in the order of account number //Creating a binary file with a structure #include <stdio.h> struct custinfo{ int accountno; char lastname[15]; char firstname[10]; double balance; ; int main(){ FILE *cfptr; struct custinfo cust; //Read created file if ( ( cfptr = fopen( "data.bin", "rb" ) ) == NULL ) printf( "File cannot be opened.\n" ); printf( "\\%-6s %-16s%-11s%10s\n", "AcctNo", "lastname", "firstname", "balance" ); do{ fread(&cust, sizeof(struct custinfo), 1,cfPtr ); if (!feof(cfptr)) //Do following if you don t want to see empty records //if (!feof(cfptr) && cust.accountno!=0) printf( "%-6d %-16s%-11s%10.2f\n", cust.accountno, cust.lastname, cust.firstname, cust.balance); while (!feof(cfptr)); fclose( cfptr ); return 0; if ( ( cfptr = fopen( "data.bin", "wb" ) ) == NULL ) printf( "File cannot be opened.\n" ); else { printf( "Enter account#: ( in a range 1-100, to exit 0) \n? " ); scanf( "%d", &cust.accountno ); while (cust.accountno!= 0 ) { printf( "Enter lastname, firstname, balance:\n? " ); fscanf( stdin, "%s%s%lf", cust.lastname, cust.firstname, &cust.balance);//stdin is keyboard fseek(cfptr,(cust.accountno-1)*sizeof(struct custinfo),seek_set); fwrite(&cust, sizeof(struct custinfo), 1,cfPtr ); printf( "Enter account #: \n? " ); scanf( "%d", &cust.accountno); fclose(cfptr); 12-53
54 Random Access Binary files have two features that distinguish them from text files: You can jump instantly to any structure in the file, which provides random access as in an array. You can change the contents of a structure anywhere in the file at any time. C supports the file-of-structures concept very cleanly. Once you open the file you can read a structure, write a structure, or seek to any structure in the file. This file concept supports the concept of a file pointer. When the file is opened, the pointer points to record 0 (the first record in the file). Any read operation reads the currently pointed-to structure and moves the pointer down one structure. Any write operation writes to the currently pointed-to structure and moves the pointer down one structure. fseek moves the pointer to the requested record. Keep in mind that C thinks of everything in the disk file as blocks of bytes read from disk into memory or read from memory onto disk. C uses a file pointer, but it can point to any byte location in the file. You therefore have to keep track of things
55 Finding a specific data //This program reads the required element from a file #include <stdio.h> #define SIZE 5 int main(){ FILE *binaryp; int x,i,numbers[size]={3,5,9,12,1; //open for writing binary binaryp = fopen("nums.bin", "wb"); if (binaryp == NULL) printf ("File 'nums.bin' cannot be opened.\n"); else { if(fwrite(numbers, sizeof (int), SIZE, binaryp)!=size) {printf("error in writing the data."); return 1; else printf("file created sucessfully.\n\n"); fclose(binaryp); //Open for reading binary binaryp = fopen("nums.bin", "rb"); if (binaryp == NULL) printf ("File 'nums.bin' cannot be opened.\n"); else { if (fread(numbers, sizeof (int),size, binaryp)!=size) { printf("error in reading file."); return 1; else printf("content of file:\n"); for (i=0; i<size;i++) printf("%d ",numbers[i]); printf("\nenter the index of the element number 0-%d:",SIZE-1); do { scanf("%d",&i); if (i<0 i>=size) printf("invalid index. please reenter.\n"); while(i<0 i>=size); //if user entered 0, pointer will stay at the beginning fseek(binaryp,i*sizeof(int),seek_set); if (fread(&x, sizeof (int),1, binaryp)!=1) { printf("error in reading file."); return 1; else printf("the value is:%d",x); fclose(binaryp); printf("\n"); return 0; 12-55
56 Updating a specific data //Updating a binary file with a structure #include <stdio.h> struct custinfo{ int accountno; char lastname[15]; char firstname[10]; double balance; ; int main(){ FILE *cfptr; struct custinfo cust; int acct; double transaction; if ( ( cfptr = fopen( "data.bin", "rb+" ) ) == NULL ) printf( "File cannot be opened.\n" ); else { printf( "Enter account# to be updated: ( in a range 1-100, to exit 0) \n? " ); scanf( "%d", &acct ); while (acct!= 0 ) { fseek(cfptr,(acct-1)*sizeof(struct custinfo),seek_set); fread(&cust, sizeof(struct custinfo), 1,cfPtr ); if (cust.accountno==0) printf("account has no information.\n"); else printf( "%-6d %-16s%-11s%10.2f\n",cust.accountNo, cust.lastname, cust.firstname, cust.balance); See next page 12-56
57 Updating a specific data (continued) printf("enter transaction + or - value:"); scanf("%lf",&transaction); cust.balance+=transaction; //update balance printf( "%-6d %-16s%-11s%10.2f\n",cust.accountNo, cust.lastname, cust.firstname, cust.balance); fseek(cfptr,(acct-1)*sizeof(struct custinfo),seek_set); fwrite(&cust, sizeof(struct custinfo), 1,cfPtr ); printf( "Enter account #: \n? " ); scanf( "%d", &acct); fclose(cfptr); //Read updated file if ( ( cfptr = fopen( "data.bin", "rb" ) ) == NULL ) printf( "File cannot be opened.\n" ); else { printf( "\n%-6s %-16s%-11s%10s\n", "AcctNo", "lastname", "firstname", "balance" ); do{ fread(&cust, sizeof(struct custinfo), 1,cfPtr ); if (!feof(cfptr)) //if (!feof(cfptr) && cust.accountno!=0) DO THIS IF YOU DON'T WANT TO SEE EMPTY RECORDS printf( "%-6d %-16s%-11s%10.2f\n",cust.accountNo, cust.lastname, cust.firstname, cust.balance); while (!feof(cfptr)); fclose( cfptr ); return 0; 12-57
58 #include <stdio.h> int main () { FILE *fp; int i,x,y=99; fp = fopen("file.bin", "wb+"); if( fp == NULL ) { printf ("Error opening file"); return (-1); //Create file with integers from 1-10 for(i=1;i<=10;i++) fwrite(&i,sizeof(int),1,fp); fseek(fp, 0, SEEK_SET); //Rewind to the beginning while (fread(&x,sizeof(int),1,fp)==1) printf("%d\n",x); printf("file is created.\n\n"); fclose(fp); fp = fopen("file.bin", "rb+"); if( fp == NULL ) { printf ("Error opening file"); return 1; printf("beginning pointer:%ld\n",ftell(fp)); if (fread(&x,sizeof(int),1,fp)==1) {printf("first value:%d\n",x); printf("pointer after reading:%ld\n",ftell(fp)); else return 1; fseek(fp,0,seek_cur); if(fwrite(&y,sizeof(int),1,fp)==1) printf("pointer after writing:%ld\n",ftell(fp)); else printf("file is not updated.\n\n"); rewind(fp); while (fread(&x,sizeof(int),1,fp)==1) printf("%d\n",x); fclose(fp); return(0);
59 Advantages of Binary files Assume that two bytes are used store an int value. 244 ( ) In text files, Write: Read: It takes more time. It takes more space. (Three bytes versus two) Precision Binary files also usually have faster read and write times than text files, because a binary image of the record is stored directly from memory to disk (or vice versa). In a text file, everything has to be converted back and forth to text, and this takes time
60 Disadvantages of Binary files A binary file created on one computer is rarely readable on another type of computers. A binary file can not be created or modified in a word processor. fread fwrite fscanf fprintf 12-60
61 References J.R. Hanly & E.B. Koffman, Problem Solving and Program Design in C (6 th Ed.), Addison- Wesley, 2010 P.J. Deitel & H.M. Deitel, C How to Program (5 th Ed.), Pearson Education, Inc.,
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 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 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 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 informationChapter 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 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 informationLecture 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 informationLecture6 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 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 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 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 informationFile 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 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 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 informationFile (1A) Young Won Lim 11/25/16
File (1A) Copyright (c) 2010-2016 Young W. Lim. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version
More 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 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 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 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 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 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 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 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 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 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 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 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 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 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 informationEM108 Software Development for Engineers
EE108 Section 4 Files page 1 of 14 EM108 Software Development for Engineers Section 4 - Files 1) Introduction 2) Operations with Files 3) Opening Files 4) Input/Output Operations 5) Other Operations 6)
More informationData File and File Handling
Types of Disk Files Data File and File Handling Text streams are associated with text-mode files. Text-mode files consist of a sequence of lines. Each line contains zero or more characters and ends with
More informationC: How to Program. Week /June/18
C: How to Program Week 17 2007/June/18 1 Chapter 11 File Processing Outline 11.1 Introduction 11.2 The Data Hierarchy 11.3 Files and Streams 11.4 Creating a Sequential Access File 11.5 Reading Data from
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 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 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 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 informationLAB 13 FILE PROCESSING
LAB 13 FILE PROCESSING School of Computer and Communication Engineering Universiti Malaysia Perlis 1 1. OBJECTIVES: 1.1 To be able to create, read, write and update files. 1.2 To become familiar with sequential
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 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 informationSTRUCTURES & FILE IO
STRUCTURES & FILE IO Structures Collections of related variables (aggregates) under one name Can contain variables of different data types Commonly used to define records to be stored in files Combined
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 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 informationUNIX System Programming
File I/O 경희대학교컴퓨터공학과 조진성 UNIX System Programming File in UNIX n Unified interface for all I/Os in UNIX ü Regular(normal) files in file system ü Special files for devices terminal, keyboard, mouse, tape,
More informationSystems Programming. 08. Standard I/O Library. Alexander Holupirek
Systems Programming 08. Standard I/O Library Alexander Holupirek Database and Information Systems Group Department of Computer & Information Science University of Konstanz Summer Term 2008 Last lecture:
More 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 informationC Basics And Concepts Input And Output
C Basics And Concepts Input And Output Report Working group scientific computing Department of informatics Faculty of mathematics, informatics and natural sciences University of Hamburg Written by: Marcus
More informationCSI 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 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 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 informationLAB 13 FILE PROCESSING
LAB 13 FILE PROCESSING School of Computer and Communication Engineering Universiti Malaysia Perlis 1 1. OBJECTIVES: 1.1 To be able to create, read, write and update files. 1.2 To become familiar with sequential
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 informationFundamentals of Programming. Lecture 15: C File Processing
1 Fundamentals of Programming Lecture 15: C File Processing Instructor: Fatemeh Zamani f_zamani@ce.sharif.edu Sharif University of Technology Computer Engineering Department The lectures of this course
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 informationCE Lecture 11
Izmir Institute of Technology CE - 104 Lecture 11 References: - C: A software Engineering Approach 1 In this course you will learn Input and Output Sorting Values 2 Input and Output Opening and Closing
More informationUNIT- 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 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 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 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 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 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 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 informationa = ^ ^ ^ ^ ^ ^ ^ 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 informationWeek 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 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 informationPreprocessing 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 informationIntroduction to file management
1 Introduction to file management Some application require input to be taken from a file and output is required to be stored in a file. The C language provides the facility of file input-output operations.
More 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 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 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 informationC 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 informationOrganization of a file
File Handling 1 Storage seen so far All variables stored in memory Problem: the contents of memory are wiped out when the computer is powered off Example: Consider keeping students records 100 students
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 information7/21/ FILE INPUT / OUTPUT. Dong-Chul Kim BioMeCIS UTA
7/21/2014 1 FILE INPUT / OUTPUT Dong-Chul Kim BioMeCIS CSE @ UTA What s a file? A named section of storage, usually on a disk In C, a file is a continuous sequence of bytes Examples for the demand of a
More informationChapter 8 File Processing
Chapter 8 File Processing Outline 1 Introduction 2 The Data Hierarchy 3 Files and Streams 4 Creating a Sequential Access File 5 Reading Data from a Sequential Access File 6 Updating Sequential Access Files
More informationDS: 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 informationBBM#101# #Introduc/on#to# Programming#I# Fall$2014,$Lecture$13$
BBM#101# #Introduc/on#to# Programming#I# Fall$2014,$Lecture$13$ Today#! File#Input#and#Output#! Strings#! Data&Files&! The&Data&Type&char&! Data&Hierarchy&! Characters&and&Integers&! Files&and&Streams&!
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 informationUNIX 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 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 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 informationFiles. 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 informationBBM#101# #Introduc/on#to# Programming#I# Fall$2013,$Lecture$13$
BBM#101# #Introduc/on#to# Programming#I# Fall$2013,$Lecture$13$ Today#! File#Input#and#Output#! Strings#! Data!Files!! The!Data!Type!char!! Data!Hierarchy!! Characters!and!Integers!! Files!and!Streams!!
More informationCS1003: Intro to CS, Summer 2008
CS1003: Intro to CS, Summer 2008 Lab #07 Instructor: Arezu Moghadam arezu@cs.columbia.edu 6/25/2008 Recap Pointers Structures 1 Pointer Arithmetic (exercise) What do the following return? given > char
More informationCSE2301. Introduction. Streams and Files. File Access Random Numbers Testing and Debugging. In this part, we introduce
Warning: These notes are not complete, it is a Skelton that will be modified/add-to in the class. If you want to us them for studying, either attend the class or get the completed notes from someone who
More 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 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 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 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 informationLaboratory: USING FILES I. THEORETICAL ASPECTS
Laboratory: USING FILES I. THEORETICAL ASPECTS 1. Introduction You are used to entering the data your program needs using the console but this is a time consuming task. Using the keyboard is difficult
More informationFile Access. FILE * fopen(const char *name, const char * mode);
File Access, K&R 7.5 Dealing with named files is surprisingly similar to dealing with stdin and stdout. Start by declaring a "file pointer": FILE *fp; /* See Appendix B1.1, pg. 242 */ header
More informationBBM 101 Introduc/on to Programming I Fall 2013, Lecture 13
BBM 101 Introduc/on to Programming I Fall 2013, Lecture 13 Instructors: Aykut Erdem, Erkut Erdem, Fuat Akal TAs: Yasin Sahin, Ahmet Selman Bozkir, Gultekin Isik 1 Today File Input and Output Strings Data
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 information8. Characters, Strings and Files
REGZ9280: Global Education Short Course - Engineering 8. Characters, Strings and Files Reading: Moffat, Chapter 7, 11 REGZ9280 14s2 8. Characters and Arrays 1 ASCII The ASCII table gives a correspondence
More informationIntroduction to Programming in C Department of Computer Science and Engineering. Lecture No. #47. File Handling
Introduction to Programming in C Department of Computer Science and Engineering Lecture No. #47 File Handling In this video, we will look at a few basic things about file handling in C. This is a vast
More informationIO = Input & Output 2
Input & Output 1 IO = Input & Output 2 Idioms 3 Input and output in C are simple, in theory, because everything is handled by function calls, and you just have to look up the documentation of each function
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 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 informationCS113: Lecture 7. Topics: The C Preprocessor. I/O, Streams, Files
CS113: Lecture 7 Topics: The C Preprocessor I/O, Streams, Files 1 Remember the name: Pre-processor Most commonly used features: #include, #define. Think of the preprocessor as processing the file so as
More informationFile I/O BJ Furman 23OCT2010
File I/O BJ Furman 23OCT2010 Learning Objectives Explain what is meant by a data stream Explain the concept of a file Open and close files for reading and writing Data Streams Data stream an ordered series
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 information