Lecture of useable
Lecture of useable
Writing data to a file: There are different I/O functions to write data
into a file if it is open in write mode.
putc function is used to write a single character to a file. For example,
putc(p,fp); Here, p is a character type variable and fp is the file pointer.
putw function is used to write an integer value to a file. For example,
putw(x,fp); Here, x is an integer type variable and fp is the file pointer.
fprintf function is used to write mixed data simultaneously. For example,
fprintf(fp, “%c %f %d”, p, 10.50,x);
File (contd.)
Reading data from a file:
getc(): p=getc(fp);
This statement reads a character from a file pointed by fp and assigns
the value to the character type variable p.
The file pointer moves by one character position for every getc/putc operation.
This function returns an end of file marker EOF, once the end of file is reached.
So, reading a file should be stopped when the EOF is encountered.
getw(): x=getw(fp); for reading an integer value from a file.
fscanf() function is used to read mixed data simultaneously.
fscanf(fp, “%f %d”, &a, &b); When the end of file is reached it returns
the value EOF.
File (contd.)
if(fp == NULL) { // file not found printf("The value is=%d ", number);
printf("Error!"); fclose(fp); // closes the file
exit(1); }
}