运行结果只能写入最后输入的学生name,xuehao,number,前面输入的怎么写不进去wen...
# include<stdio.h># include<stdlib.h>
struct STU
{
char name;
char xuehao;
char number;
};
int main(void)
{
struct STU *stu_for_write;
struct STU *stu_for_read;
stu_for_write=(struct STU *)malloc(sizeof(struct STU));
stu_for_read=(struct STU *)malloc(sizeof(struct STU));
if(stu_for_write==NULL || stu_for_read==NULL)
{
printf("分配内存失败了!");
exit(EXIT_SUCCESS);
}
for(int i=0;i<3;i++)
{
printf("请输入名字-学号-电话");
scanf("%s-%s-%s",stu_for_write->name,stu_for_write->xuehao,stu_for_write->number);
if((fp=fopen("test.txt","wb"))==NULL)
{
printf("打开文件失败!");
exit(EXIT_FAILURE);
}
fseek(fp,sizeof(struct STU)*i,SEEK_SET);
printf("%ld",ftell(fp));
fwrite(stu_for_write,sizeof(struct STU),1,fp);
fclose(fp);
}
return 0;
}
输入
xu-1-2
liu-2-3
jia-1-2
运行结束,cat test.txt,显示结果只是jia-1-2,前面输入的怎么写不进去。
#include <stdio.h>
#include <stdlib.h>
struct STU
{
char name;
char xuehao;
char number;
};
int main(void)
{
struct STU *stu_for_write;
struct STU *stu_for_read;
stu_for_write=(struct STU *)malloc(sizeof(struct STU));
stu_for_read=(struct STU *)malloc(sizeof(struct STU));
FILE *fp;
if(stu_for_write==NULL || stu_for_read==NULL)
{
printf("分配内存失败了!");
exit(EXIT_SUCCESS);
}
for(int i=0;i<3;i++)
{
printf("请输入名字-学号-电话");
scanf("%s-%s-%s",stu_for_write->name,stu_for_write->xuehao,stu_for_write->number);
if((fp=fopen("test.txt","r+"))==NULL)
{
if((fp = fopen("test.txt", "w+")) == NULL)
{
printf("无法创建文件!");
exit(EXIT_FAILURE);
}
}
fseek(fp,sizeof(struct STU)*i,SEEK_SET);
printf("%ld",ftell(fp));
fwrite(stu_for_write,sizeof(struct STU),1,fp);
fclose(fp);
}
return 0;
}
┌─────────────┬───────────────────────────────┐
│fopen() mode │ open() flags │
├─────────────┼───────────────────────────────┤
│ r │ O_RDONLY │
├─────────────┼───────────────────────────────┤
│ w │ O_WRONLY | O_CREAT | O_TRUNC│
├─────────────┼───────────────────────────────┤
│ a │ O_WRONLY | O_CREAT | O_APPEND │
├─────────────┼───────────────────────────────┤
│ r+ │ O_RDWR │
├─────────────┼───────────────────────────────┤
│ w+ │ O_RDWR | O_CREAT | O_TRUNC │
├─────────────┼───────────────────────────────┤
│ a+ │ O_RDWR | O_CREAT | O_APPEND │
└─────────────┴───────────────────────────────┘
只有 r 和 r+ 可以用,其他要么是追加,要么就是截断
那就只能先尝试打开,如果失败,那就创建
页:
[1]