c - 使用结构写入文件

标签 c file structure

我编写了一个应该写入文件的代码,但是当我执行该程序时,它显示“保存学生数据时出错”。这是代码。

#include<stdio.h>

typedef struct Student{
 int numberOfStudents;
 char name; // onoma foithth
 char surname; // epi8eto foithth


};


int main(){
    struct Student  s1; 
    FILE *file=fopen("d:\\student.txt","w");
    if(file==NULL){
        printf("error in saving student data");
        return 1;
    }
    while(1){

    printf("Enter number of students: ");
    scanf("%d",&s1.numberOfStudents);
    printf("enter name: ");
    scanf("%s",&s1.name);
    printf("enter surname: ");
    scanf("%s",&s1.surname);

    fprintf(file,"%d\t%s\t%s\n",s1.numberOfStudents,s1.name,s1.surname);
    printf("continue (Y/N)");
    char ch=getch();
    if (ch=='N' || ch=='n')
    break;
    }


    fclose(file);
    return 0;
}

我已经搜索过,但找不到问题所在。我的错误在哪里?

最佳答案

如果您想将 onoma foithth 存储在结构中,

name 字段应为 char array,如图所示。将您的结构修改为

typedef struct Student{
 int numberOfStudents;
 char name[10]; // onoma foithth
 char surname; // epi8eto foithth


};

然后在扫描name时删除&,因为name本身就是地址。

scanf("%s",s1.name);

确保您在 fopen() 中给出了正确的路径

关于c - 使用结构写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48239678/

相关文章:

c - 在结构的二维数组中分配内存时出现问题

c - 使用指针访问结构成员

指针可以存储值吗?void 指针有什么用?

c - 向量化具有间接访问的循环

c - 检查目录是否存在的便携方法 [Windows/Linux, C]

java/android - 无法访问 SD 卡上的文件

c++ - 当取消请求排队时,pthread_cancel() 将如何响应?

c - 在 C 中通过释放和重用指针转置数组

java - 我无法加载我的文件?

c - 二叉树节点以及与父节点的关系