习题
10.3 请指出以下程序段中是否有错,若有错,说明原因并改正。
(1) #include <stdio.h>
//加个头函数#include <stdlib.h>
struct rec {
int a;
char b;
};
void main() {
struct rec r;
FILE *f1, *f2;
r.a=100; r.b='G';
f1=fopen("file1.dat", 'w'); // 改为f1=fopen("file1.dat", “wb”);
if (f1==NULL) {
printf("OPEN FILE FAILURE \n");
exit(0);
}
fwrite(&r, sizeof(struct rec), 1, f1); fclose(f1);
f2=fopen("file2.dat", 'wb'); // 改为f2=fopen("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;
f1=fopen("file1.dat", "w");
if (f1==NULL) {
printf("OPEN FILE FAILURE \n");
exit(0);
}
fprintf(f1, "%s\n", s); fclose(f1);
f2=fopen("file2.dat", "w b"); // 改为f2=fopen("file2.dat", “wt”);
if (f2==NULL) {
printf("OPEN FILE FAILURE \n");
exit(0);
}
fprintf(f2, "%s\n", s); fclose(f2);
}
•3 •
10.4试编程将磁盘中的一个文本文件逐行逆置到另一个文件中。
/*例如一个文件中的数据是
abcdef
xyz
转化后的文件是:
fedcba
zyx
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
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--;
}
}
•2 •
else { // 没有换行符\n的情况
i=0;
j=len-1;
while (i<len/2) {
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 <stdio.h>
#include <string.h>
#include <stdlib.h>
#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);
}
•3 •
for (i=0; i<N; 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);
}
•2 •。