FILE INPUT and OUTPUT
Files and streams
Output from ls command is written to the file named
outfile.
2
12/12/2022
Streams, files
3
12/12/2022
Streams
4
12/12/2022
program
stdin
stdout
stderr
File access
5
12/12/2022
File access rules
6
12/12/2022
File opening and closing
7
12/12/2022
FILE
fp = fopen(“x.c”, “r”);
8
12/12/2022
Reading from a file.
char c;
fp = fopen(“x.c”, “r”);
c = fgetc(fp);
This causes reading next character from standard input, that is keyboard (by default). So, stdin is actually a file pointer.
9
12/12/2022
Modes
10
12/12/2022
Common programming Errors
11
12/12/2022
An example --- displaying contents of a file
main( )
{
FILE *fp; char ch;
fp = fopen(“x.c”, “r”);
if(fp == NULL) {
puts(“error in opening file x.c”);
exit(1);
}
while( (ch = fgetc(fp)) != EOF)
putchar(ch);
fclose(fp);
}
12
12/12/2022
Some comments about the example
13
12/12/2022
The Example --- improved
main( )
{
FILE *fp; char ch, s[64];
puts(“Enter the file to be displayed:”);
gets(s);
fp = fopen(s, “r”);
if(fp == NULL) {
puts(“error in opening file ”);
puts(s);
exit(1);
}
while( (ch = fgetc(fp)) != EOF)
putchar(ch);
fclose(fp);
}
14
12/12/2022
Can’t we further improve ?
15
12/12/2022
Writing to a file
16
12/12/2022
Copying a file -- example
main( )
{
FILE *fpr, *fpw; char ch;
fpr = fopen(“x.c”, “r”);
fpw = fopen(“y.c”, “w”);
if(fpr == NULL || fpw == NULL) {
puts(“error in opening file x.c or y.c”);
exit(1);
}
while( (ch = fgetc(fpr)) != EOF)
fputc(ch, fpw);
fclose(fpr); fclose(fpw);
}
17
12/12/2022
Character input and output functions
18
12/12/2022
Character input and output functions
19
12/12/2022
Character input and output functions
20
12/12/2022
Formatted Output and Input
21
12/12/2022
Some other operations
22
12/12/2022
Some other operations
23
12/12/2022
Other Functions
24
12/12/2022
Other Functions
Syntax
25
12/12/2022
Other Functions
#include <stdio.h>
int main()
{
FILE* fp;
fp = fopen("test.txt", "r");
// Moving pointer to end
fseek(fp, 0, SEEK_END);
// Printing position of pointer
printf("%ld", ftell(fp));
return 0;
}
26
12/12/2022
Other …
27
12/12/2022