Download presentation
Presentation is loading. Please wait.
1
ETE 132 Lecture 8 By Munirul Haque
2
Topics I/O, Streams, Files
3
Files The library stdio.h defines a structure called FILE.
You don’t need to know any of the details of how a FILE works, you just need to know how to point to them. A pointer to a file is called a “file handle”.
4
Writing to a File void main() { } FILE *fp; /* pointer to a file */
/* open WRITEME.txt for reading */ fp = fopen("WRITEME.txt", “w"); /* do stuff with the file */ fprintf(fp,"This goes in the file"); /* close the file -- it’s a good habit */ fclose(fp); }
5
fopen The function fopen accepts a string corresponding to the name of the filename, and another string the says whether we want to open the file to read ("r"), Write ("w"), or append ("a"). If there is any error, fopen returns the pointer value NULL.
6
Printf and Scanf with Files
Up to now, we’ve been using printf to print messages (to “standard output”), and scanf to receive input from the keyboard (from “standard input”). These can be generalized to the functions fprintf and fscanf, which write to and read from a particular file.
7
Printf and Scanf with Files
Given a file pointer fp, the statement: fprintf(fp,"This goes in the file"); writes to the file handled by fp. The statement: fscanf(fp,"%d",&intvar); reads an integer from the file.
8
Other ways to read and write
There are more rudimentary ways to read from files and write to files. Suppose that fp is a file pointer. The function getc(fp) returns a single character read from the file. putc(c,fp); writes the character c to the file.
9
End of File feof() returns non-zero if fp reaches end-of-file, otherwise zero. FILE *fp; while(!feof(fp)) ch = getc(ch);
10
Reading from file Reading character by character File *fp; char ch;
fp = fopen(“myfile”, “r”); // open file to read while(!feof(fp)) { // read until end-of-file ch = getc(fp); printf(“%c”,ch); } fclose(fp); // close the file stream
11
Writing to file Writing character by character fclose(fp); File *fp;
char ch; fp = fopen(“myfile”, “w”); // open file to write while(1) { scanf(“%c”, &ch); if (ch == ‘\n’) break; // read until newline found putc(ch, fp); } fclose(fp);
12
Copy file FILE *from, *to; char ch; from = fopen(“input.txt”, “r”); to = fopen(“output.txt”, “w”); while (!feof(from)) { ch = getc(from); putc (ch, to); } fclose(from); fclose(to);
13
fscanf() Read from file to specific variables double d; int i;
char str[20], ch; FILE *fp; fscanf(fp, “%lf %d %s %c”, &d, &i, str, &ch); printf(“%lf %d %s %c”, d, i, str, c); fclose(fp);
14
fprintf() Write values from variables to file double d = 1234.5;
int i = 10; char str[20] = “Hello”, ch = ‘Q’; FILE *fp; fprintf(fp, “%lf %d %s %c”, d, i, str, c); fclose(fp);
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.