首页 > 解决方案 > 从 .txt 文件中读取不同的数据类型

问题描述

我想从文本文件中读取数据并存储数据。

我不能使用所有数据,getc()因为它会一次获取所有数据,而且我不知道如何分发这些数据以供我使用。

数据形式为:
John
Sebastian
1
2 //笔记数(所以,当我读取此值并运行循环以收集所有笔记时)
12 //note 1
21 //note 2

#include <stdio.h>

struct StudentDetails
{
    char firstName[100], secondName[100];
    int notes[100][30], id;
    struct StudentDetails *next;
};

int main()
{
    FILE *input;
    input = fopen("input.txt", "r");

    if (!input)
    {

        while (input != EOF)
        {
             //what to do to store in different variable rather in one.
        }
    }
    else
    {
        printf("File not found");
    }
}

标签: c

解决方案


请尝试使用 fread() 函数从文件中读取记录和 fwrite(),它用于将记录写入文件。例如:fwrite(&sd,sizeof(sd),1,input); 学生记录不需要 struct StudentDetails *next; (我们没有做任何类似链表的事情,我们只是在一个文件中写入不同的学生记录。所以你只需在 main 中将结构变量定义为 StudentDetails SD 就足够了,每次循环迭代你可以将一个学生记录写入文件。)阅读你可以使用

while(fread(&sd,sizeof(sd),1,input) > 0 )
{
   printf("Name:%s",sd.name);//this you can do ...      
}

我希望它会帮助你:)


推荐阅读