第10章的习题答案
- 格式:doc
- 大小:255.50 KB
- 文档页数:4
• 3 • 习 题
10.3 请指出以下程序段中是否有错,若有错,说明原因并改正。
(1) #include stdio.h加个头函数#include stdlib.h
struct rec {
int a;
char b;
};
void main() {
struct rec r;
FILE f1, f2;
r.a100; r.bG;
f1fopen(file1.dat, w); // 改为f1fopen(file1.dat, “wb”);
if (f1==NULL) {
printf("OPEN FILE FAILURE \n");
exit(0);
}
fwrite(&r, sizeof(struct rec), 1, f1); fclose(f1);
f2fopen(file2.dat, wb); // 改为f2fopen(file2.dat, “wb”);
if (f2==NULL) {
printf("OPEN FILE FAILURE \n");
exit(0);
}
fwrite(&r, sizeof(struct rec), 1, f2); fclose(f2);
}
(2) #include stdio.h加个头函数#include stdlib.h
void main() {
char s[5]ABCD;
FILE f1, f2;
f1fopen(file1.dat, w);
if (f1==NULL) {
printf("OPEN FILE FAILURE \n");
exit(0);
}
fprintf(f1, s\n, s); fclose(f1);
f2fopen(file2.dat, wb); // 改为f2fopen(file2.dat, “wt”);
if (f2==NULL) {
printf("OPEN FILE FAILURE \n");
exit(0);
}
fprintf(f2, s\n, s); fclose(f2);
}
• 2 • 10.4 试编程将磁盘中的一个文本文件逐行逆置到另一个文件中。
/*例如一个文件中的数据是
abcdef
xyz
转化后的文件是:
fedcba
zyx
*/
#include
#include
#include
void main() {
FILE *fp_r;
char line[100], ch;
int i=0, j, len;
fp_r=fopen("F:\\file1.txt", "rt");
if (fp_r==NULL) {
printf("cannot open the file1");
exit(0);
}
fp_w=fopen("F:\\file2.txt", "wt");
if (fp_w==NULL) {
printf("cannot open the file2");
exit(0);
}
while (fgets(line, sizeof(line), fp_r)!=0) {
len=strlen(line);
if (line[len-1]=='\n') { // 有换行符\n的情况
i=0;
j=len-2;
while (i<(len-1)/2) {
ch=line[i];
line[i]=line[j];
line[j]=ch;
i++;
j--;
}
}
• 3 • else { // 没有换行符\n的情况
i=0;
j=len-1;
while (i ch=line[i]; line[i]=line[j]; line[j]=ch; i++; j--; } } fputs(line, fp_w); } fclose(fp_r); fclose(fp_w); } 10.6 某班有34名学生,期末考试科目有数学、英语、C语言和计算机原理四门课程。试编一个程序,将这34名学生的姓名、学号及各科考试成绩存入一个文件中。 #include #include #include #define N 34 struct student { int num; char name[20]; float score[4]; }; struct student stu; void main() { FILE *fp_w; int i; char string[20]; fp_w=fopen("F:\\file2.dat", "wb"); if (fp_w==NULL) { printf("cannot open the file2"); exit(0); } • 2 • for (i=0; i printf("enter student number: "); gets(string); stu.num=atoi(string); printf("enter name: "); gets(); printf("enter score: "); scanf("%f%f%f%f", &stu.score[0], &stu.score[1], &stu.score[2], &stu.score[3]); getchar(); fwrite(&stu, sizeof(struct student), 1, fp_w); } fclose(fp_w); }