Data Files. Computer Basics

Size: px
Start display at page:

Download "Data Files. Computer Basics"

Transcription

1 Unit 10 Data Files Computer Basics

2 Contents What is a data file? Basic operations with data files: Opening a data file Closing a data file Types of data files Text Files Reading text files Writing text files Binary Files Reading binary files Writing binary files Computer Basics - 2

3 What is a data file? Related information stored on auxiliary memory devices (hard disks, diskettes, CDs, flash pens,...). They allow the user to store information permanently, and to access and alter that information whenever necessary In C, an extensive set of library functions is available for creating and processing data files Reading from a data file is a similar operation to reading data entered by the keyboard Writing to a data file is a similar operation to writing data on the screen Will be using sequential files Operations with data files: Opening a data file: fopen() Closing a data file: fclose() Reading data files: fscanf(), fread() Writing data files: fprintf(), fwrite() Computer Basics - 3

4 Basic operations with data files But when working with a data file: The first step is to establish a buffer area In the buffer area information is stored while being transferred between the computer s memory and the data file The buffer area is established by writing: FILE *ptvar; Where: FILE (uppercase letters required) is a special structure type that establishes the buffer area. The structure contains all the information needed by the functions that handle data files Included in stdio.h ptvar is a pointer variable that indicates the beginning of the buffer area. The pointer ptvar is often referred to as a stream pointer, or simply a stream Computer Basics - 4

5 Basic operations with data files Opening a data file: fopen() A data file must be opened before it can be created or processed Once the data file is opened and until it is closed it is possible to carry out as many operations as the user desires without any further call to the function The library function fopen: Associates the file name with the buffer area Also specifies how the data file will be utilized, i.e., as a read-only file, a write-only file, or a read/write file, in which both operations are permitted Computer Basics - 5

6 Basic operations with data files Opening a data file: fopen() It has this prototype: FILE *fopen (char * file_name, char *mode); file_name is a string of characters that make up a valid filename and may include a path especification mode is a string that determines how the file will be opened (see next slide) The fopen() function returns a pointer: Error: null pointer Success: pointer to the beginning of the buffer area associated with the file Computer Basics - 6

7 Basic operations with data files Opening a file: Mode r Open an existing file for reading only w Open a new file for writing only. If a file with the specified file_name currently exists, it will be destroyed and a new file created in its place a Open an existing file for appending (i.e., for adding information at the end of the file). A new file will be created if the file with the specified file_name does not exist r+ Open an existing file for both reading and writing w+ Open a new file for both reading and writing. If a file with the specified file_name currently exists, it will be destroyed and a new file created in its place a+ Open a new file for both reading and appending. A new file will be created if the file with the specified file_name does not exist b Add to any of the previous modes when working with a binary file Computer Basics - 7

8 Basic operations with data files Closing a data file: fclose() Closes a file that was opened by a call to fopen() Writes any data still remaining in the buffer to the file an does a formal operating-system-level close on the file Disconnects the file from the program and frees the pointer to the file Frees the buffer area, making it available for reuse Failure to close a file invites all kind of trouble, including lost data, destroyed files, and possible intermittent errors in your program Before changing the present access mode to a data file, it has to be closed and opened again with the new access mode parameter Do not open a file more than once if it has not been previously closed Computer Basics - 8

9 Basic operations with data files Closing a data file: fclose() It has this prototype: int fclose(file *ptvar); ptvar: file pointer returned by the call to the function fopen() that opened the file that the user wants to close now The fclose() function returns: 0: if the close operation has been successful EOF: if an error has ocurred In either case, the operation is completed Generally, fclose() will fail only when a disk has been prematurely removed from the drive or there is no more space on the disk Computer Basics - 9

10 Basic operations with data files #include <stdio.h> int main(void) FILE *pfile; pfile = fopen( data.dat, w ); Declaring a pointer to a file Opening the data.dat file for writing (w) if (pfile == NULL) Checking the outcome of the opening operation printf( \n Error cannot open the designated file );... /* The file is used for writing */ /* File processing is terminated */ if (fclose(pfile)!= 0) printf( \n Error on closing the file ); return 0; Combining the call to the closing operation and its outcome Computer Basics - 10

11 Types of data files Types of data files: Text Named collection of characters saved in secondary storage (e.g., on a disk). The characters can be interpreted as individual data items, or as components of strings or numbers. A text file has no fixed size Can be viewed using a text editor Binary A file created by executing a program that stores directly in the file the computer s internal representation of each file component Only understandable by a program with information on the type, format, and structure of the file data elements Cannot be created or modified in a word processor Negative side to binary file usage: A binary file created on one computer system might not be readable on another type of computer Text files are readable and portable, but they do not use disk space as efficiently as binary files. In a text file, numbers are stored on the disk as strings instead of as numerical values Example: integer type variable with a value of (text: 8 bytes; binary: 4 bytes). Computer Basics - 11

12 Types of data files Creating a file: A data file must be created before it can be processed Ways to create a file: Directly: Using a text editor or a word processor (only valid for text files) Indirectly: Writing a program that enters information into the computer and then writes it out to the data file (text and binary files) Different library functions are used for reading and writing text and binary files: Text files: fprintf, fscanf, getc, putc, fgets, fputs Binary files: fwrite, fread, fseek Computer Basics - 12

13 Text Files Consisting of consecutive ASCII characters Data file opening and closing See previous slides Since the files consist of strings: Library functions for reading and writing strings already discussed can be utilized The pointer to the buffer area has to be included as an additional parameter putc(character, pointer) getc(pointer) fputs(string, pointer) fgets(string, number of characters, pointer) fprintf(pointer, control string, variables) fscanf(pointer, control string, variables) Computer Basics - 13

14 Text Files Functions fprintf() and fscanf( ): The function itself converts the stream of ASCII characters into the binary integers, type double mantissas and exponents, and characters strings that are the representation in main memory of the same data, and vice versa fprintf(): Behaves exactly like printf() except that it operates with a file that has to be specified Returned value: Success: returns the number of bytes written on the data file Failure: returns EOF fscanf(): Behaves exactly like scanf() except that it operates with a file that has to be specified Returned value: Success: returns the number of data items successfully assigned a value Failure: returns 0 (no values assigned to data items) EOF: if the end of file has been reached Computer Basics - 14

15 Text Files /* Program: Reads the file "pepe.txt" that contains floating-point numbers and adds them up*/ #include <stdio.h> int main(void) int n; /* Value returned by fscanf */ FILE *pfile; /* Pointer to file */ double num1,num2; /* numbers read from the data file */ double sum; /* Sum of the numbers */ pfile = fopen("pepe.txt", "r+"); if (pfile == NULL) printf("error: Cannot open \"pepe.txt\"\n"); else sum = 0.; /* Initializing the sum to 0*/ n = fscanf(pfile, %lf %lf", &num1,&num2); while (n!= EOF ) /* iterate until an end of file is detected */ sum+=num1+num2; n = fscanf(pfile, %lf%lf ", &num1,&num2); printf( The sum is: %lf\n", sum); if( fclose(pfile)!= 0) printf("error on closing the file\n"); return(0); If pepe.txt contains: The result would be: The sum is: Computer Basics - 15

16 Text Files Functions fgets(), fputs(), getc() or fgetc(), putc() or fputc() They are functions that write or read a character (fgetc(), getc(), fputc(), putc()) or a string (fgets(), fputs()) No format conversion takes place (they work with characters) Reading a character: int fgetc(file *pointer_to_file) or int getc(file *pointer_to_file) Returns the next character from the file pointed by pointer_to_file Returned value: Success: character just read Failure: returns EOF EOF: if the end of the file is reached Writing a character: int fputc(int ch, FILE * pointer_to_file) or int putc(int ch, FILE * pointer_to_file) Write the character ch to the file pointed by pointer_to_file Returned value: Success: character just written Error: EOF Computer Basics - 16

17 Text Files #include <stdio.h> #include <stdlib.h> #include <ctype.h> int main(void) FILE *point; char c; point=fopen("data.txt","w"); if (point==null) else printf("\n ERROR cannot open the designated file"); do c = toupper(getchar()); putc(c, point); while (c!= '\n'); if (fclose(point)!= 0) return (0); printf("error on closing the file"); Computer Basics - 17

18 Text Files /* Program: PrintFile * Description: Reads the contents of a data file on a character-by-character basis, * and displays them on the screen */ #include <stdio.h> #define SIZE_STRING 256 int main(void) char file_name[size_string]; /* Name of the file to be opened */ char letter; /* character read from the data file, and displayed on the screen */ FILE *pfile; /* Pointer to the file to be printed */ printf( Enter the name of the file: "); gets(file_name); pfile = fopen(file_name, "r"); if (pfile == NULL) printf("error on opening the file \"%s\"\n", file_name); else letter = fgetc(pfile); while(letter!= EOF) printf("%c", letter); letter = fgetc(pfile); fclose(pfile); return (0); Computer Basics - 18

19 Text Files Reading a string: char * fgets(char *str, int num, FILE *pointer_to_file). Reads up to num-1 characters from the file pointed by pointer_to_file and stores them in the character array pointed by str Characters are read until either a newline ( \n ) or an EOF is received or until the specified limit is reached. After the characters have been read, a null ( \0 ) is stored in the array immediately after the last character read. If fgets has room to store the entire string, it will include \n before \0. If the string is truncated, no \n is stored Returned value: Success: str (pointer to the string) Failure or EOF reached: a NULL pointer Writing a string: int fputs(const char *str, FILE *pointer_to_file) Writes the contents of the string pointed to by str to the file pointed by pointer_to_file. The null terminator ( \0 ) is not written Returned value: Success: nonnegative number Error: EOF Computer Basics - 19

20 Text Files #include <stdio.h> #include <ctype.h> #include <stdlib.h> int main(void) Example 1: OPTION A, Program that enters a string from the keyboard, then writes it out to a data file. Finally, the string is read back from the file and displayed on the screen FILE *point; char str[80]; char str2[80]; point=fopen( sample.dat","w"); if (point==null) printf("\n Error CANNOT OPEN THE FILE FOR WRITING"); else puts("\nenter a string (CR to quit):\n"); gets(str); fputs(str,point); if (fclose(point)!= 0) printf( Error on closing the file ); else point=fopen( sample.dat","r"); if (point==null) printf("\nerror - CANNOT OPEN THE FILE FOR READING"); else fgets(str2,80,point); puts("\nthe file has been read and contains:\n"); puts(str2); if (fclose(point)!= 0) printf( Error on closing the file ); return (0); Computer Basics - 20

21 #include<stdlib.h> #include <stdio.h> #include <ctype.h> int main(void) Text Files FILE *point; char str[80]; char str2[80]; Example 1: OPTION B, Program that enters a string from the keyboard, then writes it out to a data file. Finally, the string is read back from the file and displayed on the screen point=fopen( sample.txt","w+"); // For reading and writing if (point==null) else printf("\n Error CANNOT OPEN THE FILE FOR READING AND WRITING"); puts("\nenter a string (CR to quit) :\n"); gets(str); fputs(str,point); /* reset the file position indicator to start of the file */ rewind(point); WATCH OUT! fgets(str2,80,point); puts("\nthe file has been read and contains:\n"); puts(str2); if (fclose(point)!= 0) printf( Error on closing the file ); return(0); Computer Basics - 21

22 Text Files #include <stdio.h> #include <ctype.h> #define SIZE 80 int main(void) FILE *point; char str[size]; char str2[size]; char file_name[size]; int n; printf( Enter a name for the file ); gets(file_name); point=fopen(file_name,"w"); if (point == NULL) printf("\n Error Cannot open file for writing ); else puts("\nenter a string (CR to quit):\n"); gets(str); fprintf(point,"%s\n",str); if (fclose(point)!= 0) printf( Error on closing the file ); else point=fopen(file_name,"r"); if (point == NULL) printf("\n Error Cannot open file for reading"); else puts("\nthe file has been read and contains:\n"); n = fscanf(point, %[^\n]\n",str2); if (n == EOF n == 0) printf( Error on reading string 2 ); else puts(str2); if (fclose(point)!= 0) printf( Cannot close the file ); return(0); Computer Basics - 22

23 Text Files Example: Storing structures in text files #include <stdio.h> #include <stdlib.h> #include <string.h> #define N 2 /* Size of the array of structures (Number of products) */ /* Declaring a structure for the products */ typedef struct char name[12]; double price; T_PROD; int main(void) T_PROD product [N]; /* Array of products in the warehouse */ int i; /* counter for looping*/ FILE *f; /* File descriptor for the text file */ /*** Initializing the array of structures ***/ strcpy(product[0].name,"cd Rosana"); product [0].price=25.63; strcpy(product[1].name,"cd Titanic"); product[1].price=26.28; The text file would contain: CD Rosana CD Titanic /*** Creating the file ***/ f = fopen("data.txt","w"); if (f ==NULL) printf( Cannot open file data.txt\n"); else for (i = 0; i<n; i++) fprintf(f,"%s\n",product[i].name); fprintf(f,"%.2f\n",product[i].price); fclose(f); return(0); Computer Basics - 23

24 Binary Files Data elements in a binary file are stored as they are in memory A binary file cannot be created, modified or viewed (only by sheer luck a combination of 8 consecutive bits might represent an existing character code) Permit to organize data into blocks containing contiguous bytes of information These blocks can represent complex data structures, such as arrays and structures Are declared in exactly the same way as text files. The open and close functions are used just as they are used for text files stdio However, different stdio library functions are used for writing fwrite() and reading fread() of blocks of any type of data size_t fwrite(void *buffer, size_t num_bytes, size_t count, FILE *fp); size_t fread (void *buffer, size_t num_bytes, size_t count, FILE *fp); For fwrite(), buffer is a pointer to the information that will be written to the file. For read(), buffer is a pointer to a region of memory that will receive the data from the file The value of count determines how many items are read or written, with each item being num_bytes bytes in length fp is a pointer to a previously opened file Computer Basics - 24

25 fread() function Example 1 // Program that reads all the records in a file items.dat // and displays the contents on the screen // The number of records is not known in advance #include <stdio.h> #include <stdlib.h> typedef struct char name[20]; int stock; float unit_price; T_ITEM; int main(void) FILE *p_file; T_ITEM item; if((p_file = fopen ("items.dat", "rb"))==null) printf("error. Cannot open designated read file\n"); else while(fread(&item, sizeof(t_item), 1, p_file) == 1) printf("\nname of the item => %s\n", item.name); printf("number of items => %d\n", item.stock); printf("unit price => %.2f\n", item.unit_price); fclose(p_file); return 0; In the example, we take into consideration that fread() returns the number of items actually read. If fewer elements are read than are requested in the call, either an error has occurred or the end of the file has been reached. In this case, only 1 element is read, consequently the while loop keeps reading new records until the value returned by fread() is different from 1. Computer Basics - 25

26 fread() function Example 2 #include <stdio.h> #include <stdlib.h> int main(void) FILE *fp; int i; double bal[5] = 1.1, 2.2, 3.3, 4.4, 5.5; fp=fopen("test.dat", "wb+"); if (fp==null) printf("\ncannot open designated write file\n"); else fwrite(bal, sizeof(double), 5, fp); rewind(fp); if(fread(bal, sizeof(double), 5, fp)!=5) printf("\nfile read error\n"); else for(i=0; i<5; i++) printf("%.2f ", bal[i]); The program writes five double numbers from the bal array to a disk file called test and then reads them back. The value returned by fread() 5 in this case is used to test the outcome of the read operation. The example illustrates the point that fread() may return values different from 1. fclose(fp); return 0; Computer Basics - 26

27 Binary Files Example: Storing structures in binary files #include <stdio.h> #include <stdlib.h> #include <string.h> #define N 2 /* Size of the array of structures (number of products) */ /* Declaring a structure for the products */ typedef struct char name[12]; double price; T_PROD; int main(void) T_PROD product [N]; /* Array of products in the warehouse */ int i; /* counter for looping*/ FILE *f; /* File descriptor for the binary file */ /*** Initializing the array of structures ***/ strcpy(product [0].name,"CD Rosana"); product[0].price=25.63; strcpy(product[1].name,"cd Titanic"); product[1].price=26.28; Outcome: you need to write a program to show the information recorded on disk /*** Creating the file ***/ f=fopen("data.dat","wb"); if (f==null) else Opening in binary mode printf( Cannot open file data.dat\n"); for(i=0; i<n; i++) fwrite(&product[i], sizeof(product[i]),1,f); fclose(f); return(0); Address of the structure to be written to the file Size of the structure Computer Basics - 27

28 Binary Files #include <stdio.h> #include <stdlib.h> typedef struct char name[30]; int age; T_RECORD; int main(void) FILE *point; T_RECORD record; T_RECORD record2; point=fopen( info.dat","wb"); if (point==null) printf("\n Cannot open the file "); else printf( Enter name:\n"); gets(record.name); printf( Enter age:\n"); scanf("%d\n",&record.age); fwrite(&record, sizeof(t_record), 1, point); if (fclose(point)!= 0) printf( Error on closing the file ); else point=fopen( info.dat","rb"); if (point==null) printf("\n Cannot open the file "); else puts("\nthe contents of the file are:\n"); fread(&record2, sizeof(t_record), 1, point); printf("name: "); puts(record2.name); printf( AGE: "); printf("%d",record2.age); if (fclose(point)!= 0) printf( Error on closing the file ); return (0); Computer Basics - 28

29 Binary Files #include <stdio.h> #include <stdlib.h> #define N 5 typedef struct char name[30]; int age; T_RECORD; int main(void) FILE *point; T_RECORD record [N]; int count; Reading one structure at a time point=fopen( test.dat","wb"); if (point==null) printf("\n Cannot open file "); else for (count=0;count<n;count++) fflush(stdin); printf( Enter name %d:\n, count+1); gets(record[count].name); printf( Enter age %d:\n, count+1); scanf("%d",&record[count].age); fwrite(&record[count], sizeof(t_record), 1, point); Example Option 1 fclose(point) ; point=fopen( test.dat ","rb"); if (point==null) printf("\ncannot open file for reading "); else puts("\nthe contents of the file are:\n"); for (count=0;count<n;count++) fread(&record[count], sizeof(t_record),1,point); printf("name %d:, count+1); puts(record [count].name); printf( AGE %d:, count+1); printf( %d\n, record[count].age); fclose(point); return(0); Computer Basics - 29

30 Binary Files #include <stdio.h> #include <stdlib.h> #define N 5 typedef struct char name[30]; int age; T_RECORD; int main(void) FILE *point; Reading all the N structures with a single fread() T_RECORD record [N]; int count; point=fopen( test.dat","wb"); if (point==null) printf("\n Cannot open file "); else for (count=0;count<n;count++) fflush(stdin); printf( Enter name %d:\n, count+1); gets(record[count].name); printf( Enter age %d:\n, count+1); scanf("%d",&record[count].age); fwrite(&record[count], sizeof(t_record), 1, point); Example Option 2 fclose(point) ; point=fopen( test.dat ","rb"); if (point==null) printf("\ncannot open file for reading "); else puts("\nthe contents of the file are:\n"); fread(record, sizeof(t_record), N, point); for (count=0;count<n;count++) printf("name %d:, count+1); puts(record [count].name); printf( AGE %d:, count+1); printf( %d\n, record[count].age); fclose(point); return(0); Computer Basics - 30

31 fseek() and Random-Access I/O Random read and write operations can be performed using the C I/O system with the help of fseek(), which sets the file position indicator to point to any record in the file Prototype: size_t fseek(file *fp, long int displacement, int origin); fp : It is a file pointer returned by a call to fopen() displacement : Number of bytes from origin, which will become the new current position origin : Defined by one of the following arguments: SEEK_SET: Count from the beginning of the file SEEK_CUR: Count from the current pointer position SEEK_END: Count from the end of the file Returned value: Success: 0 (the file pointer has moved properly) Failure: a nonzero value Example: fseek(fp,sizeof(t_product,seek_set); /* Points to second record in file */ fseek(fp,9*sizeof(t_product),seek_set); /* Points to the 10th product */ fseek(fp,2*sizeof(t_product),seek_cur); /* Skips 2 products */ Computer Basics - 31

32 fseek(): a short example typedef struct char name[40]; char street [30]; char city[30]; char province[20]; int postal_code; T_INFO; The following function seeks to the specified structure of type T_INFO void find(int client_num) FILE *fp; T_INFO info; if((fp=fopen("mail.dat", "rb"))==null) printf("cannot open file.\n"); else // find the proper structure fseek(fp, client_num*sizeof(t_info), SEEK_SET); // read data into memory fread(&info, sizeof(t_info), 1, fp); fclose(fp); Computer Basics - 32

33 Binary Files: Example of fseek() #include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct char name[30]; int age; T_RECORD; void Enter_data (T_RECORD record[ ]); void Display_data (T_RECORD record[ ]); void Create_file (T_RECORD record[ ]); void Load_file (T_RECORD record[ ]); void Update_file (void); int main(void) T_RECORD record[10]; Enter_data(record); Create_file(record); Display_data(record); Update_file(); Load_file(record); Display_data(record); return(0); void Enter_data (T_RECORD record[ ]) int count; printf( Enter name and age for 5 people: \n"); for (count=0;count<5;count++) fflush(stdin); printf( Enter name of person %d:\n, count+1); gets(record[count].name); printf( Enter age of person %d:\n, count+1); scanf("%d",&record [count].age); return; void Display_data (T_RECORD record[ ]) int count; printf("\n:::::present contents of the file:\n"); for (count=0;count<5;count++) printf("name %d:, count+1); puts(record[count].name); printf( AGE %d:, count+1); printf("%d\n",record[count].age); return; 1/4 Computer Basics - 33

34 Binary Files: Example of fseek() void Create_file(T_RECORD record[ ]) FILE *point; int count; printf("\nwriting INFO TO THE DATA FILE...\n"); point=fopen( info.dat","wb"); if (point==null) printf("\nerror on opening the file"); else for(count=0;count<5;count++) fwrite(&record[count],sizeof(t_record),1,point); /* An alternative to previous loop fwrite(record,sizeof(t_record),5,point); */ printf("\n:::::file CREATED SUCCESSFULLY:::::\n"); fclose(point); return; 2/4 void Load_file(T_RECORD record[ ]) FILE *point; int count=0; printf("\nreading THE FILE...\n"); point=fopen( info.dat","rb"); if (point==null) printf("\n Error on opening the file"); else while ( fread(&record[count],sizeof(t_record), 1,point) == 1) count++; printf("\n:::::file READ SUCCESSFULLY:::::\n"); fclose(point) ; return; Computer Basics - 34

35 Binary Files: Example of fseek() void Update_file(void) FILE *point; T_RECORD record; int count=0; char str[30]; 3/4 fflush(stdin); printf("\nenter name to search for:\n"); gets(str); printf("\nreading THE FILE AND SEARCHING FOR NAME OF THE PERSON...\n"); point=fopen( info.dat","rb+"); if (point==null) printf("\nerror"); else do fread(&record,sizeof(t_record),1,point); count++; while ((strcmp(record.name,str)!=0)&&(count<5)); (CONTINUES IN NEXT SLIDE) Computer Basics - 35

36 Binary Files: Example of fseek() if (strcmp(record.name,str)==0) printf("\n...name FOUND...\n"); printf("\n...current DATA:\n"); printf("name: %s\n",record.name); printf( AGE: %d\n",record.age); printf("\n:::::enter NEW DATA:::::::::\n"); fflush(stdin); printf( Enter name:\n"); gets(record.name); printf( Enter age:\n"); scanf("%d",&record.age); printf("\n...updating DATA FILE...\n"); fseek(point,(count-1)*sizeof(t_record),seek_set); fwrite(&record,sizeof(t_record),1,point); printf("\n...file UPDATING COMPLETED...\n"); else printf("\n::::name NOT FOUND IN THE FILE::::\n"); fclose(point); return; 4/4 Computer Basics - 36

37 feof() function Determines when the end of the file pointed by fp has been encountered Prototype: int feof (FILE *fp); fp : It is a file pointer returned by a call to fopen() Returned value: any value different from 0 (true): if the end of the file has been reached (we try to read a record and an EOF is encountered) 0: otherwise (a record is read normally) Permits to read a file when the number of records is not known in advance, by reading records until the end of the file is encountered feof() can be applied to binary files as well as text files Computer Basics - 37

38 feof(): example of binary file // Program that illustrates the use of the function feof() with a binary file #include <stdio.h> typedef struct char name[15]; int stock; double unit_price; T_ITEM; int main(void) FILE *fp; T_ITEM item; fp = fopen("items.dat", "rb"); if(fp==null) printf("\nerror. Cannot open designated read file\n"); else fread(&item, sizeof(t_item), 1, fp); while(!feof(fp)) printf("\nname=%-15s Stock=%d Price=%7.2f", item.name, item.stock, item.unit_price); fread(&item, sizeof(t_item), 1, fp); fclose(fp); return 0; Computer Basics - 38

39 feof(): example of text file // Program that illustrates the use of the function feof() with a text file #include <stdio.h> int main(void) FILE *fp; char name[15]; int stock; double unit_price; fp = fopen("items.txt", "r"); if(fp==null) printf("\nerror. Cannot open designated read file\n"); else fscanf(fp,"%s %d %lf", name, &stock, &unit_price); while(!feof(fp)) printf("\nitem=%-15s Stock=%3d Price=%8.2f", name, stock, unit_price); fscanf(fp,"%s %d %lf", name, &stock, &unit_price); fclose(fp); return 0; Computer Basics - 39

40 APPENDIX Computer Basics - 40

41 Function fgets() (1/4) Format: fgets(s, n, stream) One of the uses of this function is to assure that the number of characters assigned to a string variable is not exceeded This function copies characters from stream into the string s until it has read n-1 characters or a newline character, whichever comes first. The terminator '\0' is automatically added at the end of the string s Example (for reading data from the keyboard): fgets (book.title, 20, stdin); fgets behaves a bit differently from gets. Consider this code fragment: char line [80]; printf ( Type in a line of data.\n > ); gets(line); Computer Basics - 41

42 Function fgets() (2/4) If the user responds to the prompt as follows, Type in a line of data. > Here is a short sentence. The value stored in line would be Here is a short sentence. \0... The \n character representing the <return> or <enter> key pressed at the end of the sentence is not stored. Like scanf, gets() can overflow its string argument if the user enters a longer data line that will fit. The stdio library s file version of gets(), fgets(), behaves somewhat differently. Function fgets takes three arguments: the output parameter string, a maximum number of characters to store (n) and the file pointer to the data file. Function fgets() will never store more than n 1 characters from the data file, and the final character stored will always be '\0'. However, the next to last character may or may not be '\n'. If fgets() has room to store the entire line of data, it will include '\n' before '\0'. If the line is truncated, no '\n' is stored. Computer Basics - 42

43 Function fgets() (3/4) As mentioned earlier, when using gets(), it is possible to overrrun the array that is being used to receive the characters entered by the user because gets() provides no bounds checking. When used with stdin (to read from the keyboard), the fgets() function offers an useful alternative because it can limit the number of characters read and then prevents overrruns. The only trouble is that fgets() does not remove the newline character and gets() does, so you will have to manually remove it to avoid unwanted line jumps when the information is shown, for example, on the screen. Function Clean_String(char *string) can be used to remove the unwelcome newline character '\n'. Or the following code: lg=strlen(string); if(string[lg-1]== \n string[lg-1]= \0 ; Computer Basics - 43

44 Function fgets() (4/4) Code of Clean_String(): void Clean_String (char *string) int i=0; while(string[i]!= \n && string[i]!= \0 ) i++; if(string[i]== \n string[i]= \0 ; Example of the use of the above function is illustrated with the following group of instructions: printf("intro DNI of salesman => "); fgets(salesman.dni,10,stdin); Clean_String(salesman.dni); Computer Basics - 44

Fundamentals of Programming. Lecture 10 Hamed Rasifard

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

More information

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

Mode Meaning r Opens the file for reading. If the file doesn't exist, fopen() returns NULL. Files Files enable permanent storage of information C performs all input and output, including disk files, by means of streams Stream oriented data files are divided into two categories Formatted data

More information

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

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

More information

EM108 Software Development for Engineers

EM108 Software Development for Engineers EE108 Section 4 Files page 1 of 14 EM108 Software Development for Engineers Section 4 - Files 1) Introduction 2) Operations with Files 3) Opening Files 4) Input/Output Operations 5) Other Operations 6)

More information

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

Content. Input Output Devices File access Function of File I/O Redirection Command-line arguments File I/O Content Input Output Devices File access Function of File I/O Redirection Command-line arguments UNIX and C language C is a general-purpose, high-level language that was originally developed by

More information

System Software Experiment 1 Lecture 7

System Software Experiment 1 Lecture 7 System Software Experiment 1 Lecture 7 spring 2018 Jinkyu Jeong ( jinkyu@skku.edu) Computer Systems Laboratory Sungyunkwan University http://csl.skku.edu SSE3032: System Software Experiment 1, Spring 2018

More information

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

UNIT IV-2. The I/O library functions can be classified into two broad categories: UNIT IV-2 6.0 INTRODUCTION Reading, processing and writing of data are the three essential functions of a computer program. Most programs take some data as input and display the processed data, often known

More information

Darshan Institute of Engineering & Technology for Diploma Studies Unit 6

Darshan Institute of Engineering & Technology for Diploma Studies Unit 6 1. What is File management? In real life, we want to store data permanently so that later on we can retrieve it and reuse it. A file is a collection of bytes stored on a secondary storage device like hard

More information

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

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

More information

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

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 12 BIL 104E Introduction to Scientific and Engineering Computing Lecture 12 Files v.s. Streams In C, a file can refer to a disk file, a terminal, a printer, or a tape drive. In other words, a file represents

More information

Data File and File Handling

Data File and File Handling Types of Disk Files Data File and File Handling Text streams are associated with text-mode files. Text-mode files consist of a sequence of lines. Each line contains zero or more characters and ends with

More information

File Handling. Reference:

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

More information

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

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

More information

Input/Output and the Operating Systems

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

More information

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

Unit 6 Files. putchar(ch); ch = getc (fp); //Reads single character from file and advances position to next character 1. What is File management? In real life, we want to store data permanently so that later on we can retrieve it and reuse it. A file is a collection of bytes stored on a secondary storage device like hard

More information

2009 S2 COMP File Operations

2009 S2 COMP File Operations 2009 S2 COMP1921 9. File Operations Oliver Diessel odiessel@cse.unsw.edu.au Last updated: 16:00 22 Sep 2009 9. File Operations Topics to be covered: Streams Text file operations Binary file operations

More information

C-Refresher: Session 10 Disk IO

C-Refresher: Session 10 Disk IO C-Refresher: Session 10 Disk IO Arif Butt Summer 2017 I am Thankful to my student Muhammad Zubair bcsf14m029@pucit.edu.pk for preparation of these slides in accordance with my video lectures at http://www.arifbutt.me/category/c-behind-the-curtain/

More information

Introduction to file management

Introduction to file management 1 Introduction to file management Some application require input to be taken from a file and output is required to be stored in a file. The C language provides the facility of file input-output operations.

More information

PROGRAMMAZIONE I A.A. 2017/2018

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

CS240: Programming in C

CS240: Programming in C CS240: Programming in C Lecture 13 si 14: Unix interface for working with files. Cristina Nita-Rotaru Lecture 13/Fall 2013 1 Working with Files (I/O) File system: specifies how the information is organized

More information

Lecture 9: File Processing. Quazi Rahman

Lecture 9: File Processing. Quazi Rahman 60-141 Lecture 9: File Processing Quazi Rahman 1 Outlines Files Data Hierarchy File Operations Types of File Accessing Files 2 FILES Storage of data in variables, arrays or in any other data structures,

More information

M.CS201 Programming language

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

More information

Computer Programming Unit v

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

More information

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

Quick review of previous lecture Ch6 Structure Ch7 I/O. EECS2031 Software Tools. C - Structures, Unions, Enums & Typedef (K&R Ch. 1 Quick review of previous lecture Ch6 Structure Ch7 I/O EECS2031 Software Tools C - Structures, Unions, Enums & Typedef (K&R Ch.6) Structures Basics: Declaration and assignment Structures and functions

More information

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

File I/O. Arash Rafiey. November 7, 2017 November 7, 2017 Files File is a place on disk where a group of related data is stored. Files File is a place on disk where a group of related data is stored. C provides various functions to handle files

More information

C Programming Language

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

More information

25.2 Opening and Closing a File

25.2 Opening and Closing a File Lecture 32 p.1 Faculty of Computer Science, Dalhousie University CSCI 2132 Software Development Lecture 32: Dynamically Allocated Arrays 26-Nov-2018 Location: Chemistry 125 Time: 12:35 13:25 Instructor:

More information

Standard File Pointers

Standard File Pointers 1 Programming in C Standard File Pointers Assigned to console unless redirected Standard input = stdin Used by scan function Can be redirected: cmd < input-file Standard output = stdout Used by printf

More information

Accessing Files in C. Professor Hugh C. Lauer CS-2303, System Programming Concepts

Accessing Files in C. Professor Hugh C. Lauer CS-2303, System Programming Concepts Accessing Files in C Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie, Absolute C++, by Walter

More information

File IO and command line input CSE 2451

File IO and command line input CSE 2451 File IO and command line input CSE 2451 File functions Open/Close files fopen() open a stream for a file fclose() closes a stream One character at a time: fgetc() similar to getchar() fputc() similar to

More information

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

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

More information

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

Files and Streams Opening and Closing a File Reading/Writing Text Reading/Writing Raw Data Random Access Files. C File Processing CS 2060 CS 2060 Files and Streams Files are used for long-term storage of data (on a hard drive rather than in memory). Files and Streams Files are used for long-term storage of data (on a hard drive rather than

More information

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

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

More information

File I/O. Preprocessor Macros

File I/O. Preprocessor Macros Computer Programming File I/O. Preprocessor Macros Marius Minea marius@cs.upt.ro 4 December 2017 Files and streams A file is a data resource on persistent storage (e.g. disk). File contents are typically

More information

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

CSI 402 Lecture 2 Working with Files (Text and Binary) CSI 402 Lecture 2 Working with Files (Text and Binary) 1 / 30 AQuickReviewofStandardI/O Recall that #include allows use of printf and scanf functions Example: int i; scanf("%d", &i); printf("value

More information

Input / Output Functions

Input / Output Functions CSE 2421: Systems I Low-Level Programming and Computer Organization Input / Output Functions Presentation G Read/Study: Reek Chapter 15 Gojko Babić 10-03-2018 Input and Output Functions The stdio.h contain

More information

MARKS: Q1 /20 /15 /15 /15 / 5 /30 TOTAL: /100

MARKS: 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 information

7/21/ FILE INPUT / OUTPUT. Dong-Chul Kim BioMeCIS UTA

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

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

Organization of a file

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

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

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

More information

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

CSci 4061 Introduction to Operating Systems. Input/Output: High-level CSci 4061 Introduction to Operating Systems Input/Output: High-level I/O Topics First, cover high-level I/O Next, talk about low-level device I/O I/O not part of the C language! High-level I/O Hide device

More information

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

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

More information

UNIX System Programming

UNIX System Programming File I/O 경희대학교컴퓨터공학과 조진성 UNIX System Programming File in UNIX n Unified interface for all I/Os in UNIX ü Regular(normal) files in file system ü Special files for devices terminal, keyboard, mouse, tape,

More information

CSI 402 Systems Programming LECTURE 4 FILES AND FILE OPERATIONS

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

More information

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

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

More information

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

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

More information

Ch 11. C File Processing (review)

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

More information

HIGH LEVEL FILE PROCESSING

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

More information

Chapter 10. File Processing 248 FILE PROCESSING

Chapter 10. File Processing 248 FILE PROCESSING Chapter 10 FILE PROCESSING LEARNING OBJECTIVES After reading this chapter the reader will be able to understand the need of data file. learn the operations on files. use different data input/output functions

More information

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

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

More information

Standard C Library Functions

Standard C Library Functions Demo lecture slides Although I will not usually give slides for demo lectures, the first two demo lectures involve practice with things which you should really know from G51PRG Since I covered much of

More information

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

ENG120. Misc. Topics

ENG120. Misc. Topics ENG120 Misc. Topics Topics Files in C Using Command-Line Arguments Typecasting Working with Multiple source files Conditional Operator 2 Files and Streams C views each file as a sequence of bytes File

More information

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

CSE2301. Introduction. Streams and Files. File Access Random Numbers Testing and Debugging. In this part, we introduce Warning: These notes are not complete, it is a Skelton that will be modified/add-to in the class. If you want to us them for studying, either attend the class or get the completed notes from someone who

More information

C File Processing: One-Page Summary

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

More information

C programming basics T3-1 -

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

More information

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

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

More information

Computer programming

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

More information

Engineering program development 7. Edited by Péter Vass

Engineering program development 7. Edited by Péter Vass Engineering program development 7 Edited by Péter Vass Functions Function is a separate computational unit which has its own name (identifier). The objective of a function is solving a well-defined problem.

More information

Procedural Programming

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

Computer System and programming in C

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

More information

EECS2031. Modifiers. Data Types. Lecture 2 Data types. signed (unsigned) int long int long long int int may be omitted sizeof()

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

Day14 A. Young W. Lim Tue. Young W. Lim Day14 A Tue 1 / 15

Day14 A. Young W. Lim Tue. Young W. Lim Day14 A Tue 1 / 15 Day14 A Young W. Lim 2017-12-26 Tue Young W. Lim Day14 A 2017-12-26 Tue 1 / 15 Outline 1 Based on 2 C Strings (1) Characters and Strings Unformatted IO Young W. Lim Day14 A 2017-12-26 Tue 2 / 15 Based

More information

Week 9 Lecture 3. Binary Files. Week 9

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

More information

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

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

More information

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

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

More information

Intermediate Programming, Spring 2017*

Intermediate Programming, Spring 2017* 600.120 Intermediate Programming, Spring 2017* Misha Kazhdan *Much of the code in these examples is not commented because it would otherwise not fit on the slides. This is bad coding practice in general

More information

Chapter 11 File Processing

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

More information

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

fopen() fclose() fgetc() fputc() fread() fwrite() The ability to read data from and write data to files is the primary means of storing persistent data, data that does not disappear when your program stops running. The abstraction of files that C provides

More information

C mini reference. 5 Binary numbers 12

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

Introduction to Computer Programming Lecture 18 Binary Files

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

More information

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

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

More information

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

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

More information

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

File (1A) Young Won Lim 11/25/16 File (1A) Copyright (c) 2010-2016 Young W. Lim. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version

More information

Programming Fundamentals

Programming Fundamentals Programming Fundamentals Day 4 1 Session Plan Searching & Sorting Sorting Selection Sort Insertion Sort Bubble Sort Searching Linear Search Binary Search File Handling Functions Copyright 2004, 2 2 Sorting

More information

Naked C Lecture 6. File Operations and System Calls

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

More information

CP2 Revision. theme: file access and unix programs

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

More information

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

Systems Programming. 08. Standard I/O Library. Alexander Holupirek Systems Programming 08. Standard I/O Library Alexander Holupirek Database and Information Systems Group Department of Computer & Information Science University of Konstanz Summer Term 2008 Last lecture:

More information

CE Lecture 11

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

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

Standard I/O in C, Computer System and programming in C Standard I/O in C, Contents 1. Preface/Introduction 2. Standardization and Implementation 3. File I/O 4. Standard I/O Library 5. Files and Directories 6. System Data Files and Information 7. Environment

More information

Lecture6 File Processing

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

More information

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

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

More information

Laboratory: USING FILES I. THEORETICAL ASPECTS

Laboratory: 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 information

Programming & Data Structure

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

More information

Fundamentals of Programming & Procedural Programming

Fundamentals of Programming & Procedural Programming Universität Duisburg-Essen PRACTICAL TRAINING TO THE LECTURE Fundamentals of Programming & Procedural Programming Session Seven: Strings and Files Name: First Name: Tutor: Matriculation-Number: Group-Number:

More information

C Basics And Concepts Input And Output

C Basics And Concepts Input And Output C Basics And Concepts Input And Output Report Working group scientific computing Department of informatics Faculty of mathematics, informatics and natural sciences University of Hamburg Written by: Marcus

More information

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

File Access. FILE * fopen(const char *name, const char * mode); File Access, K&R 7.5 Dealing with named files is surprisingly similar to dealing with stdin and stdout. Start by declaring a "file pointer": FILE *fp; /* See Appendix B1.1, pg. 242 */ header

More information

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

Physical Files and Logical Files. Opening Files. Chap 2. Fundamental File Processing Operations. File Structures. Physical file. File Structures Physical Files and Logical Files Chap 2. Fundamental File Processing Operations Things you have to learn Physical files and logical files File processing operations: create, open, close,

More information

Topic 8: I/O. Reading: Chapter 7 in Kernighan & Ritchie more details in Appendix B (optional) even more details in GNU C Library manual (optional)

Topic 8: I/O. Reading: Chapter 7 in Kernighan & Ritchie more details in Appendix B (optional) even more details in GNU C Library manual (optional) Topic 8: I/O Reading: Chapter 7 in Kernighan & Ritchie more details in Appendix B (optional) even more details in GNU C Library manual (optional) No C language primitives for I/O; all done via function

More information

Fundamentals of Programming. Lecture 15: C File Processing

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

CSC 270 Survey of Programming Languages. Input and Output

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

More information

Day14 A. Young W. Lim Thr. Young W. Lim Day14 A Thr 1 / 14

Day14 A. Young W. Lim Thr. Young W. Lim Day14 A Thr 1 / 14 Day14 A Young W. Lim 2017-11-02 Thr Young W. Lim Day14 A 2017-11-02 Thr 1 / 14 Outline 1 Based on 2 C Strings (1) Characters and Strings Unformatted IO Young W. Lim Day14 A 2017-11-02 Thr 2 / 14 Based

More information

UNIT- 2. Binary File

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

More information

CSCI 171 Chapter Outlines

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

Procedural Programming & Fundamentals of Programming

Procedural Programming & Fundamentals of Programming & Fundamentals of Programming Exercise 4 (SS 2018) 12.06.2018 What will I learn in the 5. exercise Files Math functions Dynamic data structures (linked Lists) Exercise(s) 1 Files A file can be seen as

More information

Pointers cause EVERYBODY problems at some time or another. char x[10] or char y[8][10] or char z[9][9][9] etc.

Pointers cause EVERYBODY problems at some time or another. char x[10] or char y[8][10] or char z[9][9][9] etc. Compound Statements So far, we ve mentioned statements or expressions, often we want to perform several in an selection or repetition. In those cases we group statements with braces: i.e. statement; statement;

More information

Goals of this Lecture

Goals of this Lecture I/O Management 1 Goals of this Lecture Help you to learn about: The Unix stream concept Standard C I/O functions Unix system-level functions for I/O How the standard C I/O functions use the Unix system-level

More information

I/O Management! Goals of this Lecture!

I/O Management! Goals of this Lecture! I/O Management! 1 Goals of this Lecture! Help you to learn about:" The Unix stream concept" Standard C I/O functions" Unix system-level functions for I/O" How the standard C I/O functions use the Unix

More information

CSC209H Lecture 3. Dan Zingaro. January 21, 2015

CSC209H Lecture 3. Dan Zingaro. January 21, 2015 CSC209H Lecture 3 Dan Zingaro January 21, 2015 Streams (King 22.1) Stream: source of input or destination for output We access a stream through a file pointer (FILE *) Three streams are available without

More information