Download presentation
Presentation is loading. Please wait.
1
C Input / Output Prabhat Kumar Padhy
1 1
2
C Input / Output? C only has no provision for I/O.
char name[5][100]; C Input / Output? C only has no provision for I/O. Then printf and scanf possess what ? So these functions are actually are standard library funcions and there are many as well. The numerous library functions available for I/O can be classified into as the below. Console I/O functions Disk I/O functions Port I/O functions
3
Console Input and Output Functions
Formatted Functions Unformatted Functions Type Input Output Char Scanf() Printf() Int Float String Type Input Output Char getch() getche() getchar() fgetchar() putch() putchar() Int Float String gets() puts()
4
C Format Specifiers Datatype Specifier Integer short signed
char name[5][100]; C Format Specifiers Datatype Specifier Integer short signed short unsigned long signed long unsigned unsigned hexadecimal unsigned octal %d %u %ld %lu %x %o Float double %f %lf Signed char Unsigned char %c String %s
5
C Input / Output? main() { main() printf(“\n %f%f%f”,5.0,13.5,133.9);
int weight=63; printf(“\n weight is %d kg”,weight); printf(“\n weight is %2d kg”,weight); printf(“\n weight is %4d kg”,weight); printf(“\n weight is %6d kg”,weight); printf(“\n weight is %-6d kg”,weight); } main() { printf(“\n %f%f%f”,5.0,13.5,133.9); printf(“\n %f%f%f”,305.0,1200.9,3005.3); } printf(“\n %10.1f%0.1f%0.1f”,5.0,13.5,133.9); printf(“\n %0.1f%0.1f%0.1f”,305.0,1200.9,3005.3); char str1[] = “IIIT”; char str2[] = “Sricity”; char str3[] = “Delhi” printf(“\n %20sf%20sf”,str1,str2); printf(“\n %20sf%20sf”,str1,str3);
6
C Format Specifiers Esc Seq Purpose \n New line \t Tab \b Backspace \r
char name[5][100]; C Format Specifiers main() { char ch=‘a’; int i=125; float a = 12.44; char s[] = “hello world”; printf(\n%c%d%f”,ch,ch,ch); printf(\n%s%d%f”,s,s,s); printf(\n%c%d%f”,i,i,i); printf(\n%f%d\n”,a,a); } Esc Seq Purpose \n New line \t Tab \b Backspace \r Carriage return \f Form feed \a Alert \’ Single Quote \” Double quote \\ Backslash
7
sprintf() and sscanf()
char name[5][100]; sprintf() and sscanf() main() { char ch=‘A’; int i=12; float a = 3.14; char str[30]; printf(\n%d%c%f”,i,ch,a); sprintf(str,”%d%c%f”,i,ch,a); printf(\n”%s”,str); } Printf prints on the console, where as sprintf() stores them in a string Sscanf(), is counter part of sprintf(). It allows us to read characters from a string and to convert and store them in C variables according to specifiers It is a good tool for doing in-memory conversions of characters.
8
Example Program: sprintf, sscanf
printf("\n\n Your name ( Format - Without MiddleName) : %s %s",firstname,lastname); //printing extracted firstname and lastname printf("\n\n____________________________________________________________________"); printf("\n\n Enter Date of Birth (Format : dd/mm/yyyy e.g. 21/09/2002) : "); gets(bdate); //reading birth-date in string format sscanf(bdate,"%2d/%2d/%4d",&day,&month,&year); //reading data from bdate string and extracting to individual int variables day,month & year printf("\n\n Date of Birth (Format - YYYY-MM-DD) : %d-%d-%d",year,month,day); //self-explained - see output printf("\n\n Date of Birth (Format - MM-DD-YYYY) : %d-%d-%d",month,day,year); printf("\n\n"); return 0; } /*C Program#134 - sscanf() & sprintf() functions in C. 1. sscanf() reads characters from an array & stores them in different arguments. 2. sprintf() prints data items in the form of characters into an array. #include<stdio.h> int main() { char fullname[60],shortname[30],firstname[20],middlename[20],lastname[20]; char bdate[10]; int day,month,year; printf("\n\n Enter Full Name (FirstName MiddleName LastName) : "); gets(fullname); //reading fullname with spaces. sscanf(fullname,"%s %s %s",firstname,middlename,lastname); //reading firstname,middlename & lastname from fullname sprintf(shortname,"%.1s. %.1s. %s",firstname,middlename,lastname); //printing firstname and middlename initials with lastname into shortname
9
C Format Specifiers Datatype Input Function Purpose char getch()
getche() fgetchar() getchar() Gets a character from keyboard as soon as it is entered, no need of ENTER key Similar to getch(), except echoes the character on screen. Gets the character and echoes on screen, requires ENTER key A macro similar to fgetchar() string gets() Accepts a string until enter key is pressed Output Function Char putch () fputchar() putchar() Prints the character on screen A macro works similar to putch() and fputchar() puts() Outputs a string to the screen
10
Disk I/O Functions There are two types of Disk I/O available
char name[5][100]; Disk I/O Functions There are two types of Disk I/O available Standard I/O or Stream I/O – high level System I/O – low level Basic difference between them is, in high level buffer management is automatically done but in other case, programmer is expected to do. A FILE is a place on the physical disk where information is stored. Why file is needed ? When a program is terminated, the in-memory data is lost. Storing in a file will preserve your data even for later usage. For a large number of data, it will take a lot of time to enter them all. However, if you have a file containing all the data, you can easily access the contents of the file using few commands in C. Moving data from one computer to another without any changes is possible Types of FILE Text File Binary File
11
Functions for File operations
Input / Output Datatypes handled Level Usage getc() Input Characters High putc) fgetc() fputc() fscanf() Characters, strings, numbers , records fprintf() fread() fwrite() read() Chunk of byte data Low write()
12
File Opening Modes FILE *fptr; fptr = fopen(“fileopen_name”,”mode”);
For Ex: fopen(“file_name”,”mode”); Closing a file fclose(fptr); Mode Operation Returns “r”/”rb” Reading from a file NUUL, if no file “w”/”wb” Writing into a file Overwrites if file exist and new file is created otherwise “a”/”ab” Appending new contents at EOF New file is created if no file exist “r+”/”rb+” Reading existing contents. Writing new and modifying existing ones “w+”/”wb+” Writing and Reading “a+”/”ab+” Reading existing contents. Appending new at EOF and can not modify existing ones
13
File Opening Modes with flag for low level
For Ex: Open(“temp.dat”,OREAD|O_BINARY) Mode Operation O_APPEND Opens a file for appending O_CREATE Creates a file for both writing (no effect if no file is present) O_RDONLY Creates a file for both writing only O_RDWR Creates a file for both reading and writing O_WRONLY O_BINARY Creates a file in binary mode O_TEXT Creates a file in text mode
14
Reading from a text file
/* C program to read a text file */ #include <stdio.h> #include <stdlib.h> int main() { int num; FILE *fptr; if ((fptr = fopen("C:\\program.txt","r")) == NULL){ printf("Error! opening file"); // Program exits if the file pointer returns NULL. exit(1); } fscanf(fptr,"%d", &num); printf("Value of n=%d", num); fclose(fptr); return 0;
15
Writing to a text file /* C program to read a text file */
#include <stdio.h> #include <stdlib.h> int main() { int num; FILE *fptr; fptr = fopen("C:\\program.txt","w"); if(fptr == NULL) printf("Error!"); exit(1); } printf("Enter num: "); scanf("%d",&num); fprintf(fptr,"%d",num); fclose(fptr); return 0;
16
Reading from a bin file: fread()
for(n = 1; n < 5; ++n) { fread(&num, sizeof(struct threeNum), 1, fptr); printf("n1: %d\tn2: %d\tn3: %d", num.n1, num.n2, num.n3); } fclose(fptr); return 0; #include <stdio.h> #include <stdlib.h> struct threeNum { int n1, n2, n3; }; int main() int n; struct threeNum num; FILE *fptr; if ((fptr = fopen("C:\\program.bin","rb")) == NULL){ printf("Error! opening file"); // Program exits if the file pointer returns NULL. exit(1); }
17
Writing to a bin file: fwrite()
for(n = 1; n < 5; ++n) { num.n1 = n; num.n2 = 5*n; num.n3 = 5*n + 1; fwrite(&num, sizeof(struct threeNum), 1, fptr); } fclose(fptr); return 0; #include <stdio.h> #include <stdlib.h> struct threeNum { int n1, n2, n3; }; int main() int n; struct threeNum num; FILE *fptr; if ((fptr = fopen("C:\\program.bin","wb")) == NULL){ printf("Error! opening file"); // Program exits if the file pointer returns NULL. exit(1); }
18
File Operations – fseek()
char name[5][100]; File Operations – fseek() Getting data using fseek() If there are many records inside a file and need to access a record at a specific position, you need to loop through all the records before it to get the record, which will waste memory and operation time. Syntax of fseek() fseek(FILE * stream, long int offset, int whence) Different Whence in fseek Whence Meaning SEEK_SET Starts the offset from the beginning of the file. SEEK_END Starts the offset from the end of the file. SEEK_CUR Starts the offset from the current location of the cursor in the file.
19
Example program: fseek()
// Moves the cursor to the end of the file fseek(fptr, -sizeof(struct threeNum), SEEK_END); for(n = 1; n < 5; ++n) { fread(&num, sizeof(struct threeNum), 1, fptr); printf("n1: %d\tn2: %d\tn3: %d\n", num.n1, num.n2, num.n3); fseek(fptr, -2*sizeof(struct threeNum), SEEK_CUR); } fclose(fptr); return 0; #include <stdio.h> #include <stdlib.h> struct threeNum { int n1, n2, n3; }; int main() int n; struct threeNum num; FILE *fptr; if ((fptr = fopen("C:\\program.bin","rb")) == NULL){ printf("Error! opening file"); // Program exits if the file pointer returns NULL. exit(1); }
20
Questions?
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.