如何读取文件中的数据,并将其传递给结构体~>C [英] How to read through data in a file, and pass it to a struct ~> C
问题描述
好的.我的主目录中有一个名为Graduates.txt"的文件.
我有一个可移植的程序来查找主目录,我打开文件进行阅读.
文件中的数据如下所示:
Okay. I have a file called "Graduates.txt" in my home directory.
I have a portable program to find the home directory, and I opened the file for reading.
Data in the file looks something like this:
year,firstName,lastName
我需要从这个文件中获取这些数据,并将其分离到我的结构中:
I need to get this data from this file, and separate it into my struct:
typedef struct alumnus {
int yearGraduated;
char firstName[30];
char lastName[30];
} Alumns;
我有一个想法,可能行得通,也可能行不通:
while 循环读取文件,使用 fgets() 获取数据.然后它将它复制到结构......但我不知道如何实现这些.
I have a thought that may or may not work:
A while loop reads through the file, using fgets() to get the data. It then copies it to the struct... but I don't know how to implement any of this.
抱歉,如果这听起来像个愚蠢的问题,那很可能是.
Sorry if this sounds like dumb question, it most likely is.
推荐答案
#include <stdio.h>
typedef struct alumnus {
int yearGraduated;
char firstName[30];
char lastName[30];
}Alumns;
int main(void) {
Alumns REC1;
FILE *fptr;
fptr = fopen("Test.txt", "r");
fscanf(fptr, "%d,%s,%s", &REC1.yearGraduated, REC1.firstName, REC1.lastName);
printf("%d, %s, %s", REC1.yearGraduated, REC1.firstName, REC1.lastName);
}
使用 dasblinkenlight 提示实现.
Implemented using dasblinkenlight hint.
这篇关于如何读取文件中的数据,并将其传递给结构体~>C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!