我的程序必须做两件事: 输入一个点并输出最多四个点。 该文件只能打开一次。 但如果我想读点,没有任何事情发生。 我做错了什么?
#include<stdio.h>
#include<stdlib.h>
#define file "datei.dat"
struct{
float x;
float y;
float z;
}point;
void output(FILE *save){
while(fread(&point, sizeof(point), 4, save) != 4){
printf("x-coordinatee: %f",point.x);
printf("y-coordinate: %f",point.y);
printf("z-coordinate: %f",point.z);
printf("\n\n");
}
fclose(save);
}
void input(FILE *save){
printf("x-coordinate:");
scanf("%f", &point.x);
printf("y-coordinate:");
scanf("%f", &point.y);
printf("z-coordinate:");
scanf("%f", &point.z);
fseek(save, 0, SEEK_END);
if(fwrite(&point, sizeof(point), 1, save) != 1){
fprintf(stderr, "Error...!!!\n");
return;
}
}
int main(void){
char choice;
FILE *save;
save = fopen("file","w+");
if(save == NULL){
fprintf(stderr," \"file\" could not be opened!\n");
return;
}
while(1){
printf("Input:\n\n");
printf("-n- Add new point\n");
printf("-l- Output points\n");
printf("-q- End program\n\n");
printf("Your choice: ");
scanf("%c", &choice);
if(choice == 'q'){
break;
}
switch(choice){
case 'n' : input(save); break;
case 'l' : output(save); break;
default: printf("Unknown Input\n"); break;
}
fflush(stdin);
}
system("PAUSE");
return 0;
}
答案 0 :(得分:3)
你的函数output()
中有三个错误。首先,您需要回放文件。其次,fread()
读取的项目数必须为!=0
或==1
。第三,你在这个函数中而不是在程序结束时关闭了文件。
void output(FILE *save){
fseek(save, 0, SEEK_SET); // added line
while(fread(&point, sizeof(point), 1, save) != 0){ //corrected
printf("x-coordinate: %f",point.x);
printf("\ty-coordinate: %f",point.y); // better layout
printf("\tz-coordinate: %f",point.z);
printf("\n\n");
}
//fclose(save); // move to main()
}
此外,文件打开命令未使用您的#define
,请从“文件”中删除引号。
save = fopen(file,"w+"); // corrected
答案 1 :(得分:0)
问题是您致电fread()
。你把调用放在一个while循环中,直到它成功读取4个元素才会结束。您没有测试feof()
。
尝试:
void output(FILE *save){
while(1) {
if (fread(&point, sizeof(point), 1, save) == 1) {
printf("x-coordinatee: %f",point.x);
printf("y-coordinate: %f",point.y);
printf("z-coordinate: %f",point.z);
printf("\n\n");
}
else
break;
}
fclose(save);
}