Вы находитесь на странице: 1из 14

File

Prepared by:
Johra Muhammad Moosa
Lecturer
Department of Computer Science & Engineering
Bangladesh University of Engineering & Technology
Stream
 Abstraction between hardware and programmer
 Actual device providing I/O is file
 Stream is a logical interface to a file
 When a C program started operating system opens three files and
associated streams
 Standard input: stdin
 Standard output: stdout
 Standard error: stderr
 Declared in stdio.h
Open a File
FILE *fopen (char *filename, char *mode);
 Stdio.h
 Filename
 path
 Mode
 “r”, “w”, “a”, “rb”, “ab”, “r+”
 Consequence of those modes
 Returns a pointer to the opened file
 If fails returns NULL
Mode
 Read mode ("r")
 if file is unavailable error
 Write mode (“w")
 if file is unavailable created
 Append mode (“a")
 if file is unavailable created
Close a File
int fclose (FILE *fp);
 In order to improve efficiency most file system write data to disk
one sector at a time
 fclose flushes the buffer
Read/Write a Character
int fgetc (FILE *fp);
 fgetc(stdin) same as getchar()

int fputc (int ch, FILE *fp);


 fputc(‘a’, stdout) same as putchar(‘a’)
An example
 reading a text file and displaying it in the screen
#include <stdio.h>
int main(void)
{
FILE *fp;
if ((fp = fopen ("a.txt", "r"))!=NULL){
while (! feof (fp)){
putchar (fgetc(fp));
}
fclose (fp);
}
return 0;
}
End of File
int feof (FILE *fp);
 Returns non zero if fp reached end of file

int ferror (FILE *fp);


Writing and reading strings and others
int fputs (char *str, FILE *fp);

int fgets (char *str, int num, FILE *fp);


Write (fputs)
#include <stdio.h>
int main(void)
{
FILE *fp;
if ((fp = fopen ("a.txt", "w"))!=NULL){
fputs("Write test", fp);
fclose (fp);
}
return 0;
}
Read (fgets)
#include <stdio.h>
int main(void)
{
FILE *fp;
char str[80];
if ((fp = fopen ("a.txt", "w"))!=NULL){
fputs("Write test", fp);
fclose (fp);
}
if ((fp = fopen ("a.txt", "r"))!=NULL){
fgets(str, 4, fp);
fclose (fp);
printf(str);
}
return 0;
}
Writing and reading strings and others
int fprintf (FILE *fp, format speci, variable(s));
 Just like printf.
 Return
 ON SUCCESS: the number of bytes output
 ON FAILURE: returns EOF
int fscanf (FILE *fp, format speci, address(es));
 Just like scanf.
 Return
 ON SUCCESS: Number of scanned inputs.
 ON FAILURE: fscanf returns EOF
fprintf & fscanf
#include <stdio.h>
int main(void)
{
FILE *fp;
int n, x;
scanf("%d", &n);
if ((fp = fopen ("a.txt", "w"))!=NULL){
fprintf(fp, "%d", n);
fclose (fp);
}
if ((fp = fopen ("a.txt", "r"))!=NULL){
fscanf(fp, "%d", &x);
fclose (fp);
printf("\n%d\n", x);
}
return 0;
}
File Operations
 File handle : FILE *
 Open a file : fopen
 Input/Output
 Character IO : getc, putc
 String IO : fgets, fputs
 Formatted IO : fscanf, fprintf
 Raw IO : fread, fwrite
 Close a file : fclose
 Other operations :
 fflush, fseek, freopen

Вам также может понравиться