📄 24.txt
字号:
CS 1355
Introduction to Programming in C
Thursday 2006.12.7
Lecture notes (at http://r638-2.cs.nthu.edu.tw/C/notes/24.txt)
Today: Chapter 11 File I/O (continued)
- Sequential access vs Random access
File handle contains the "current position" (also called "file offset")
of accessing a file
- initially at position 0
- sequential access:
- read/write n bytes => increase offset by n
- the only way to change offset is by reading/writing sequentially.
- random access:
- move the file offset using
int fseek(FILE*, long offset, int whence)
- find out about current position using
long ftell(FILE *stream);
- three ways (whence)
- SEEK_CUR: relative to current position
- SEEK_END: relative to the end of the file
- SEEK_SET: absolute position (relative to the beginning)
Example: interactive file reading
#include <stdio.h>
int main(int argc, char **argv) {
FILE *fh;
int end = 0;
long n = 1;
if (argc != 2) {
fprintf(stderr, "usage: %s file", argv[0]); return 1;
}
if ((fh = fopen(argv[1], "r")) == NULL) {
fprintf(stderr, "can't open file %s\n", argv[1]);
return 2;
}
/* now interpret command */
while (!end) {
char c;
int i;
char line[100];
printf("%ld> ", ftell(fh));
if (fgets(line, 100, stdin) == NULL) {
end = 1;
break;
}
switch(sscanf(line, "%c%li", &c, &n)) {
case 1: /* just got %c; leave n as default */
case 2: /* c n */
switch (c) {
case 'r':
for (i = 0; i < n; i++) {
char ch;
if (!fread(&ch, 1, 1, fh)) {
end = 1;
break;
} else {
printf("%c", ch);
}
}
printf("\n");
break;
case 'g': /* SEEK_SET */
fseek(fh, n, SEEK_SET); break;
case 'c': /* SEEK_CUR */
fseek(fh, n, SEEK_CUR); break;
case 'e': /* SEEK_END */
fseek(fh, n, SEEK_END); break;
case 'q': /* quit */
end = 1;
break;
default:
printf("unknown command %c\n", c);
}
break;
case 0:
printf("syntax error\n");
case EOF:
end = 1;
break;
}
}
fclose(fh);
}
-------
Case study: a (database) transaction processing system
(Section 11.10, page 450, fig 11.16)
=> don't worry about the example. just try running it.
How it works
- create a blank file named "credit.dat" (fill 0's)
struct clientData {
int acctNum;
char lastName[15];
char firstName[10];
double balance;
};
- menu to read/write files
=> one option is to read all records in, update in array, then write all out.
=> random access: one record at a time, do not affect other records.
Points with the example
- you can write structures or any data types, not just
char, int, or other basic types
- reading structures from the file can be done in
exactly the same way for structures.
- important restriction:
- you should not store pointers in files!!
all fields should be data containers, rather than pointer variables
that is, char lastname[15] etc is ok, but
char *lastname; would not be ok!
Why not? because the pointer will probably not be meaningful
at all when you read it back into memory.
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -