Computer Programming Unit v
|
|
- Whitney York
- 5 years ago
- Views:
Transcription
1 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 available which is directly read a character or number of character from keyboard. In c language to read the input from the user, the getc( ) and getchar ( ) functions are used. getc( ): this function is used to read the character from a file stream, and return the character as an integer. Syntax int getc(file *stream); Where FILE * stream declares a file stream which is, a variable. The function returns the numeric value of the character read. If error occurs then function returns EOF. main( ) int ch; printf( Enter one character ); ch=getc(stdin); printf( the character entered is %c,ch); return 0; getchar( ) : this function is used to perform similar operation to getc( ). The getchar( ) function is equivalent to getc(stdin); This is a predefined function in C language which is available in stdio.h header file. Using this function we can read a single character from keyboard and store in character variable. When we want to read a number of character form keyboard the store all the data in a character array. Syntax int getchar(void); Where void indicates that has no arguments is needed for calling the function. 1
2 main( ) int ch1,ch2; printf( Enter two characters ); ch1=getc(stdin); ch2=getchar( ); printf( the fist character entered is : %c,ch1); printf( the Second character entered is : %c,ch2); return 0; putc( ): this function is a file handling function in C programming language which is used to write a character on standard output/screen. #include< stdio.h> int putc(int c, FILE *stream); Where the first argument, int c, indicates that the output is a character saved in an integer variable c, the second argument, File *stream, specifies a file stream. if successful, putc( ) returns the character written; otherwise, it returns EOF. main( ) int ch ch2=65; printf( the character that has numeric value of 65 is : ); putc(ch, stdout); return 0; putchar(): this function is a file handling function in C programming language which is used to write a character on standard output/screen. The only difference between the two functions is that putchar( ) needs only one argument to contain the character. There is need to specify the file stream, because the standard output (stdout) is the default file stream to putchar( ). 2
3 int putchar(int c); main( ) putchar(65); putchar(10); putchar(66); putchar(10); putchar(67); putchar(10); return 0; READING AND WRITING STRINGS gets( ) and puts( ) are used to read and write strings within the standard input and output stream. gets( ) : gets functions is used to read the string (sequence of characters) from keyboard input. Syntax char *gets(char *s); This is a predefined function in C language which is available in stdio.h header file. This function is used to read a single string from keyboard. Example: gets(string); Where the characters read from the standard input stream are stored in the character array identified by s. #include <stdio.h> int main( ) char str[100]; 3
4 printf( "Enter a value :"); gets( str ); printf( "\nyou entered: "); puts( str ); return 0; puts( ) : puts() function is used to write a line to the output screen or output stream. Syntax int puts (const char *s); Where s refers to character an array that contain a strings. The puts( ) function writes the string to the stdout. If the function is successful, it returns 0. Otherwise, a nonzero value is returned. The puts ( ) function appends a newline character to replace the null character at the end of a character array. #include <stdio.h> #include <string.h> int main() char string[40]; strcpy(str, "This is a test string"); puts(string); return 0; FORMATTED CONSOLE I/O printf() and scanf() functions comes under this category. They provide the flexibility to receive the input in some fixed format and to give the output in desired format. Formatted Console I/O functions are printf(), scanf() functions used to print and read formatted data of almost any type. Here the meaning of formatted is according to the requirement. printf() and scanf() functions are inbuilt library functions in C programming language which are available in C library by default. These functions are declared and related macros are defined in stdio.h which is a header file in C language. 4
5 Here the printf() function is used to print the formatted data on to the monitor in a required format. It takes format string, list of operands as arguments and returns an integer. Note: Here in printf(), the meaning of print is to print and f is formatted syntax printf( control specifier,variable_list); Example program int main() int x; x=printf("hello world"); /* printing 11 bytes of data */ printf("\nprinted %d Bytes of data\n",x); return 0; Output Hello world Printed 11 Bytes of data. 5
6 scanf( ) : In C programming language, scanf() function is used to read character, string, numeric data from keyboard. it is a formatted input function used to accept almost any type of data from the console input device keyboard and store into specified variable (identifier) It takes format string, list of addresses of identifiers as arguments and returns an integer. Syntax scanf( control specifier, address of the variable); Example program #include <stdio.h> int main() char ch; char str[100]; printf("enter any character \n"); scanf("%c", &ch); printf("entered character is %c \n", ch); printf("enter any string ( upto 100 character ) \n"); scanf("%s", &str); printf("entered string is %s \n", str); KEY POINTS TO REMEMBER IN C PRINTF() AND SCANF(): 1. printf() is used to display the output and scanf() is used to read the inputs. 2. printf() and scanf() functions are declared in stdio.h header file in C library. 3. All syntax in C language including printf() and scanf() functions are case sensitive. Format specifiers can be defined as the operators which are used in association with printf() function for printing the data that is referred by any object or any variable. When a value is stored within a particular variable then you cannot print the value stored in the variable straightforwardly without using the format specifiers. You can retrieve the data that are stored in the variables and can print them onto the console screen by implementing these format specifiers in a printf() function. 6
7 Format specifiers start with a percentage % operator and followed by a special character for identifying the type of the data. There are mostly several types of format specifiers that are available in C. List of format specifiers in C Format specifier Description %d Integer Format Specifier %f Float Format Specifier %c Character Format Specifier %s String Format Specifier %u Unsigned Integer Format Specifier %ld Long Int Format Specifier %g float or double format specifier %e float or double exponential format %O int unsigned octal value %P pointer address stored in pointer %X int unsigned hex value Standard C vs UNIX FILE I/O Input and output functions are process of copying the data between main memory and external devices. Input operation copies the data from input devices to main memory and output operation copies the data from memory to a device. C programming has several in-built library functions to perform input and output tasks. C was originally implemented for unix operating system. 7
8 Early versions of c support a set of I/O functions that are compatible with unix. This set of I/O functions is sometimes referred to as the UNIX-like I/O system. When c was standardized, the unix like functions were not incorporated into standard. Because they are redundant. The use of standard I/O functions has steadily risen and use of the unix-like functions has steadily decreased. Most programmers use the standard functions because they are potable to all environments. 8
9 FILES AND STREAMS File: file is a set of records that can be accessed through the set of library functions. Streams and File types: Stream means reading the data and writing the data. The streams are designed to allow the user to access the files efficiently. A stream is file or physical devices like keyboard, monitor, and printer. The file object uses these devices. The file object contains all the information about stream like current position, pointer to any buffer, error and EOF. File types There are two types of files Sequential file Random accesses file Sequential file: In this type record are kept sequentially. If we want read the last record of the file we need to read all the records before that record. It takes more time. For example if we desire to access the 10 th record then the first records should be read sequentially for reaching to 10 th record. Random access file: In this type record can be read and modified randomly. In this type if we want to read the last records of the file, we can read it directly. It takes less time as compared to sequential file. FILE SYSTEM BASICS There are different steps for file operations in c language. Opening a file Read a file Writing a file Closing a file A c language supports many more file handling functions that are available in standard library. A file represents a sequence of bytes on the disk where a group of related data is stored. File is created for permanent storage of data. In C language, we use a structure pointer of file type to declare a file. 9
10 C provides a number of functions that helps to perform basic file operations. Following are the functions, Function fopen() fclose() getc() putc() fscanf() fprintf() getw() putw() fseek() ftell() rewind() description create a new file or open a existing file closes a file reads a character from a file writes a character to a file reads a set of data from a file writes a set of data to a file reads a integer from a file writes a integer to a file set the position to desire point gives current position in the file set the position to the beginning point Syntax FILE *fp; Opening a File or Creating a File The fopen() function is used to create a new file or to open an existing file. General Syntax : FILE *fp; fp = FILE *fopen(const char *filename, const char *mode); Or FILE *fp; fp = FILE *fopen( filename, mode ); 10
11 The fopen( ) functions are used to open a file to perform operations such as reading, writing, e.t.c. This function contains two arguments and returns pointer to file, if operation is successful otherwise it cannot be opened, the fopen ( ) returns a null. Here filename is the name of the file to be opened and mode specifies the purpose of opening the file. *fp is the FILE pointer (FILE *fp), which will hold the reference to the opened(or created) file. MODE: Mode refers to operation that will be performed on the file. File can be opened in basic 3 modes i.e reading mode, writing mode, appending mode. If file is not present on the specified path then new file can be created using write and append mode. Two types of streams Text streams : A text file stores data in the form of alphabets, digits and other special symbols by storing their ASCII values and are in a human readable format. For example, any file with a.txt,.c, etc extension. A small error in a textual file can be recognized and eliminated when seen. Binary streams : binary file contains a sequence or a collection of bytes which are not in a human readable format. For example, files with.exe,.mp3, etc extension. It represents custom data. a small error in a binary file corrupts the file and is not easy to detect. 11
12 Example program for read a file using fopen( ) function # include <stdio.h> int main( ) FILE *fp ; char data[50] ; printf( "\nopening the file test.txt in read mode\n" ) ; fp = fopen( "test2.txt", "r" ) ; if ( fp == NULL ) printf( "Could not open file test.txt" ) ; return 1; printf( "\n\n\nreading the file test.txt\n\n" ) ; while( fgets ( data, 50, fp )!= NULL ) printf( "%s", data ) ; printf("\n\n\nclosing the file test.txt") ; fclose(fp) ; return 0; CLOSING A FILE: fclose( ): The fclose() function is used to close an already opened file. General Syntax : int fclose( FILE *fp ); 12
13 Here fclose() function closes the file and returns zero on success, or EOF if there is an error in closing the file. This EOF is a constant defined in the header file stdio.h. Example program for writing a file using fopen( ) function # include <stdio.h> # include <string.h> int main( ) FILE *fp ; char data[50]; printf( "Opening the file test.txt in write mode\n" ) ; fp = fopen("test.txt", "w") ; // opening an existing file if ( fp == NULL ) printf( "Could not open file test.c" ) ; return 1; printf( "\n Enter some text from keyboard\n" ) ; while ( strlen ( gets( data ) ) > 0 ) // getting input from user fputs(data, fp) ; // writing in the file fputs("\n", fp) ; printf("\nclosing the file test.c\n") ; fclose(fp) ; // closing the file return 0; 13
14 Example program for Appending a file using fopen( ) function # include <stdio.h> # include <string.h> int main( ) FILE *fp ; char data[50]; printf( "Opening the file test.txt in append mode\n" ) ; fp = fopen("test.txt", "a") ; // opening an existing file if ( fp == NULL ) printf( "Could not open file test.c" ) ; return 1; printf( "\n Enter some text from keyboard\n" ) ; while ( strlen ( gets( data ) ) > 0 ) // getting input from user fputs(data, fp) ; // writing in the file fputs("\n", fp) ; printf("\nclosing the file test.c\n") ; fclose(fp) ; // closing the file return 0; Reading and Writing function in c 14
15 C language supports the fread( ) and fwrite( ) functions to reading the file and writing the file. fwrite() function: The fwrite() function is used to write records (sequence of bytes) to the file. A record may be an array or a structure. Syntax of fwrite() function fwrite( ptr, int size, int n, FILE *fp ); The fwrite() function takes four arguments. ptr : ptr is the reference of an array or a structure stored in memory. size : size is the total number of bytes to be written. n : n is number of times a record will be written. FILE* : FILE* is a file where the records will be written in binary mode. struct Student int roll; char name[25]; float marks; ; void main() FILE *fp; char ch; struct Student Stu; fp = fopen("student.dat","w"); //Statement 1 if(fp == NULL) printf("\ncan't open file or file doesn't exist."); exit(0); do printf("\nenter Roll : "); scanf("%d",&stu.roll); 15 printf("enter Name : "); scanf("%s",stu.name);
16 printf("enter Marks : "); scanf("%f",&stu.marks); fwrite(&stu,sizeof(stu),1,fp); printf("\ndo you want to add another data (y/n) : "); ch = getche(); while(ch=='y' ch=='y'); printf("\ndata written successfully..."); fclose(fp); Output Enter Roll : 1 Enter Name : Ashish Enter Marks : Do you want to add another data (y/n) : n Data written successfully... fread() function: The fread() function is used to read bytes form the file. Syntax of fread() function fread( ptr, int size, int n, FILE *fp ); The fread() function takes four arguments. ptr : ptr is the reference of an array or a structure where data will be stored after reading. Size: size is the total number of bytes to be read from file. n : n is number of times a record will be read. FILE* : FILE* is a file where the records will be read. 16
17 Example of fread() function struct Student int roll; char name[25]; float marks; ; void main() FILE *fp; char ch; struct Student Stu; fp = fopen("student.dat","r"); //Statement 1 if(fp == NULL) printf("\ncan't open file or file doesn't exist."); exit(0); printf("\n\troll\tname\tmarks\n"); while(fread(&stu,sizeof(stu),1,fp)>0) printf("\n\t%d\t%s\t%f",stu.roll,stu.name,stu.marks); fclose(fp); Output Roll Name Marks 1 Ashish
18 FSEEK AND RANDOM ACCESS I/O The fseek() function is used to move the cursor in the file to the desired position. Syntax of fseek() function int fseek( FILE *fp, long offset, int pos ); The fseek() function takes three arguments, first is the file pointer, second is the offset that specifies the number of bytes to moved and third is the position from where the offset will move. It will return zero if successfully move to the specified position otherwise return nonzero value. There are three positions from where offset can move. #include<conio.h> void main( ) int n; FILE *fp; char ch; clrscr(); fp=fopen("file1.txt", "r"); if(fp==null) printf("file cannot be opened"); else printf("enter value of n to read last n characters"); scanf("%d",&n); fseek(fp,-n,2); 18
19 fclose(fp); getch(); while((ch=fgetc(fp))!=eof) printf("%c\t",ch); FTELL() FUNCTION IN C The ftell() function returns the current position of cursor in the file. Syntax of ftell() function ftell(file *fp); The ftell() function takes the file pointer as argument and return the current position in long type. Because of file may have more than bytes of data. The value is count from the beginning of the file. #include <stdio.h> #include <conio.h> void main () FILE *fp; int length; clrscr(); fp = fopen("file.txt", "r"); fseek(fp, 0, SEEK_END); length = ftell(fp); fclose(fp); printf("size of file: %d bytes", length); getch(); rewind () : This function is used to move the file pointer to the beginning of the given file. In other words The rewind() function is used to move the cursor at the beginning of the file. we can also use fseek() function to move the cursor at the beginning of the file. 19
20 Syntax of rewind() function void rewind(file *fp); The rewind() function takes the file pointer as argument. void main() FILE *fp; char ch; fp = fopen("file.txt","a+"); //Statement 1 if(fp == NULL) printf("\ncan't open file or file doesn't exist."); exit(0); printf("\nwrite some data :\n"); while((ch=getchar())!=eof) //Statement 2 fputc(ch,fp); rewind(fp); //Statement 3 printf("\ndata in file :\n"); while((ch = fgetc(fp))!=eof) //Statement 4 printf("%c",ch); fclose(fp); Output : Write some data: Today is sunday. Data in file : Today is sunday. 20
21 In the above example, statement 1 will create a file named file.txt in read and append mode. Statement 1 is a loop, which is writing characters to the file. Statement 4 is an another loop for reading the data. If we ignore the 3 statement, 4 statement will not display any data because after writing data in the file, pointer will be at the EOF (end-fofile). To read the data we need to move the pointer to the begining of the file. The rewind() function in statement 3 will moving the pointer to the begining of the file. FPRINTF ( ) FSCANF ( ) FUNCTIONS IN C fprintf() function So far we have seen writing of characters, strings and integers in different files. This is not enough if we need to write characters, strings and integers in one single file, for that purpose we use fprintf() function. The fprintf() function is used to write mixed type in the file. Syntax of fprintf() function fprintf(file *fp,"format-string",var-list); The fprintf() function is similar to printf() function except the first argument which is a file pointer that specifies the file to be written. void main() FILE *fp; int roll; char name[25]; float marks; char ch; fp = fopen("file.txt","w"); //Statement 1 if(fp == NULL) printf("\ncan't open file or file doesn't exist."); exit(0); do printf("\nenter Roll : "); scanf("%d",&roll); 21
22 printf("\nenter Name : "); scanf("%s",name); printf("\nenter Marks : "); scanf("%f",&marks); fprintf(fp,"%d%s%f",roll,name,marks); printf("\ndo you want to add another data (y/n) : "); ch = getche(); while(ch=='y' ch=='y'); printf("\ndata written successfully..."); fclose(fp); Output : Enter Roll : 1 Enter Name : Kumar Enter Marks : Do you want to add another data (y/n) : y Enter Roll : 2 Enter Name : Sumit Enter Marks : Do you want to add another data (y/n) : n Data written successfully... fscanf() function The fscanf() function is used to read mixed type form the file. Syntax of fscanf() function fscanf(file *fp,"format-string",var-list); The fscanf() function is similar to scanf() function except the first argument which is a file pointer that specifies the file to be read. 22
23 void main() FILE *fp; char ch; fp = fopen("file.txt","r"); //Statement 1 if(fp == NULL) printf("\ncan't open file or file doesn't exist."); exit(0); printf("\ndata in file...\n"); while((fscanf(fp,"%d%s%f",&roll,name,&marks))!=eof) //Statement 2 printf("\n%d\t%s\t%f",roll,name,marks); fclose(fp); Output : Data in file... 1 Kumar Sumit In the above example, Statement 1 will open an existing file file.txt in read mode and statement 2 will read all the data up to EOF(end-of-file) reached. THE STANDARD STREAMS Streams means reading and writing the records i.e sequence of bytes. Every runtime environment must provide three streams(such as stdin, stdout, stderr) viz standard input, standard output, standard error to every c-program. These streams are pointers to files. Streams are file or physical device such as key board, printer, monitor or screen. The streams are designed to allow the users to access the file efficiently. 23
24 File I/O Streams in C Programming Language : 1. In C all input and output is done with streams 2. Stream is nothing but the sequence of bytes of data 3. A sequence of bytes flowing into program is called input stream 4. A sequence of bytes flowing out of the program is called output stream 5. Use of Stream make I/O machine independent. Block diagram of standard streams 24
25 Standard Input Stream Device : 1. stdin stands for (Standard Input) 2. Keyboard is standard input device. 3. Standard input is data (Often Text) going into a program. 4. The program requests data transfers by use of the read operation. 5. Not all programs require input. Standard Output Stream Device : 1. stdout stands for (Standard Output) 2. Screen(Monitor) is standard output device. 3. Standard output is data (Often Text) going out from a program. 4. The program sends data to output device by using write operation. THE PREPROCESSOR DIRECTIVES # DEFINE AND #INCLUDE The preprocessor include the instructions for the compiler, these instructions are executed before the source code is compiled. Preprocessor directives begin with hash sign(#). No semicolon (;) is expected at the end of a preprocessor directive. This process is called preprocessing. In C programming language, preprocessor directive is a step performed before the actual source code compilation. It is not the part of compilation. Preprocessor directives in C programming language are used to define and replace tokens in the text and also used to insert the contents of other files into the source file. 25
26 Below is the list of preprocessor directives that C programming language offers. #define: #define is used to create symbolic constants (known as macros) in C programming language. This preprocessor command can also be used with parameterized macros. #define LESSTHAN < int main() int a = 30; if(a LESSTHAN 40) printf("a is Smaller"); return(0); 26
27 #include : #include is used to insert specific header file into C program. Advantages of pre-processor Programs becomes Readable and easy to understand. Easily modified or updated and efficient. 27
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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 informationFile IO and command line input CSE 2451
File IO and command line input CSE 2451 File functions Open/Close files fopen() open a stream for a file fclose() closes a stream One character at a time: fgetc() similar to getchar() fputc() similar to
More informationFile 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 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 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 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 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 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 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 informationC Input/Output. Before we discuss I/O in C, let's review how C++ I/O works. int i; double x;
C Input/Output Before we discuss I/O in C, let's review how C++ I/O works. int i; double x; cin >> i; cin >> x; cout
More 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 informationLecture 4. Console input/output operations. 1. I/O functions for characters 2. I/O functions for strings 3. I/O operations with data formatting
Lecture 4 Console input/output operations 1. I/O functions for characters 2. I/O functions for strings 3. I/O operations with data formatting Header files: stdio.h conio.h C input/output revolves around
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 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 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 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 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 informationCopyright The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
Chapter 18 I/O in C Standard C Library I/O commands are not included as part of the C language. Instead, they are part of the Standard C Library. A collection of functions and macros that must be implemented
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 informationComputer Programming: Skills & Concepts (CP) Files in C
CP 20 slide 1 Tuesday 21 November 2017 Computer Programming: Skills & Concepts (CP) Files in C Julian Bradfield Tuesday 21 November 2017 Today s lecture Character oriented I/O (revision) Files and streams
More informationHIGH LEVEL FILE PROCESSING
HIGH LEVEL FILE PROCESSING 1. Overview The learning objectives of this lab session are: To understand the functions used for file processing at a higher level. o These functions use special structures
More 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 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 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 informationChapter 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 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 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 informationCourse organization. Course introduction ( Week 1)
Course organization Course introduction ( Week 1) Code editor: Emacs Part I: Introduction to C programming language (Week 2-9) Chapter 1: Overall Introduction (Week 1-3) Chapter 2: Types, operators and
More informationThis code has a bug that allows a hacker to take control of its execution and run evilfunc().
Malicious Code Insertion Example This code has a bug that allows a hacker to take control of its execution and run evilfunc(). #include // obviously it is compiler dependent // but on my system
More informationComputer Programming: Skills & Concepts (CP1) Files in C. 18th November, 2010
Computer Programming: Skills & Concepts (CP1) Files in C 18th November, 2010 CP1 26 slide 1 18th November, 2010 Today s lecture Character oriented I/O (revision) Files and streams Opening and closing files
More 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 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 informationCS 261 Fall Mike Lam, Professor. Structs and I/O
CS 261 Fall 2018 Mike Lam, Professor Structs and I/O Typedefs A typedef is a way to create a new type name Basically a synonym for another type Useful for shortening long types or providing more meaningful
More informationInput/Output: Advanced Concepts
Input/Output: Advanced Concepts CSE 130: Introduction to Programming in C Stony Brook University Related reading: Kelley/Pohl 1.9, 11.1 11.7 Output Formatting Review Recall that printf() employs a control
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 informationDay14 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 informationContents. A Review of C language. Visual C Visual C++ 6.0
A Review of C language C++ Object Oriented Programming Pei-yih Ting NTOU CS Modified from www.cse.cuhk.edu.hk/~csc2520/tuto/csc2520_tuto01.ppt 1 2 3 4 5 6 7 8 9 10 Double click 11 12 Compile a single source
More 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 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 informationThe fopen command can open an external file in C language. If the file is exist, the file pointer is not NULL. Otherwise, the file pointer is NULL.
File Input / Output File open FILE *fopen( filename, mode ); The fopen command can open an external file in C language. If the file is exist, the file pointer is not NULL. Otherwise, the file pointer is
More informationSAE1A Programming in C. Unit : I - V
SAE1A Programming in C Unit : I - V Unit I - Overview Character set Identifier Keywords Data Types Variables Constants Operators SAE1A - Programming in C 2 Character set of C Character set is a set of
More informationChapter 12. Text and Binary File Processing. Instructor: Öğr. Gör. Okan Vardarlı. Copyright 2004 Pearson Addison-Wesley. All rights reserved.
Chapter 12 Text and Binary File Processing Instructor: Öğr. Gör. Okan Vardarlı Copyright 2004 Pearson Addison-Wesley. All rights reserved. Objectives We will explore the use of standard input, standard
More informationC PROGRAMMING Lecture 6. 1st semester
C PROGRAMMING Lecture 6 1st semester 2017-2018 Input/Output Most programs require interaction (input or output. I/O is not directly supported by C. I/O is handled using standard library functions defined
More informationAdvanced C Programming Topics
Introductory Medical Device Prototyping Advanced C Programming Topics, http://saliterman.umn.edu/ Department of Biomedical Engineering, University of Minnesota Operations on Bits 1. Recall there are 8
More informationBasic I/O. COSC Software Tools. Streams. Standard I/O. Standard I/O. Formatted Output
Basic I/O COSC2031 - Software Tools C - Input/Output (K+R Ch. 7) We know how to do some basic input and output: getchar - reading characters putchar - writing characters printf - formatted output Input
More informationSWEN-250 Personal SE. Introduction to C
SWEN-250 Personal SE Introduction to C A Bit of History Developed in the early to mid 70s Dennis Ritchie as a systems programming language. Adopted by Ken Thompson to write Unix on a the PDP-11. At the
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 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 informationDay14 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 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 informationC mini reference. 5 Binary numbers 12
C mini reference Contents 1 Input/Output: stdio.h 2 1.1 int printf ( const char * format,... );......................... 2 1.2 int scanf ( const char * format,... );.......................... 2 1.3 char
More informationLecture 03 Bits, Bytes and Data Types
Lecture 03 Bits, Bytes and Data Types Computer Languages A computer language is a language that is used to communicate with a machine. Like all languages, computer languages have syntax (form) and semantics
More 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 informationare all acceptable. With the right compiler flags, Java/C++ style comments are also acceptable.
CMPS 12M Introduction to Data Structures Lab Lab Assignment 3 The purpose of this lab assignment is to introduce the C programming language, including standard input-output functions, command line arguments,
More informationMODULE 3: Arrays, Functions and Strings
MODULE 3: Arrays, Functions and Strings Contents covered in this module I. Using an Array II. Functions in C III. Argument Passing IV. Functions and Program Structure, locations of functions V. Function
More informationGoals of this Lecture
I/O Management 1 Goals of this Lecture Help you to learn about: The Unix stream concept Standard C I/O functions Unix system-level functions for I/O How the standard C I/O functions use the Unix system-level
More 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 informationI/O Management! Goals of this Lecture!
I/O Management! 1 Goals of this Lecture! Help you to learn about:" The Unix stream concept" Standard C I/O functions" Unix system-level functions for I/O" How the standard C I/O functions use the Unix
More informationI/O Management! Goals of this Lecture!
I/O Management! 1 Goals of this Lecture! Help you to learn about:" The Unix stream concept" Standard C I/O functions" Unix system-level functions for I/O" How the standard C I/O functions use the Unix
More 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 informationDEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING UNIT-1
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING Year & Semester : I / II Section : CSE - 1 & 2 Subject Code : CS6202 Subject Name : Programming and Data Structures-I Degree & Branch : B.E C.S.E. 2 MARK
More informationAdvanced C Programming and Introduction to Data Structures
FYBCA Semester II (Advanced C Programming and Introduction to Data Structures) Question Bank Multiple Choice Questions Unit-1 1. Which operator is used with a pointer to access the value of the variable
More informationEngineering 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 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 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 information