好。我的主目录中有一个名为“Graduates.txt”的文件 我有一个便携式程序来查找主目录,我打开文件进行阅读 文件中的数据如下所示:
year,firstName,lastName
我需要从这个文件中获取这些数据,然后将它分成我的结构:
typedef struct alumnus {
int yearGraduated;
char firstName[30];
char lastName[30];
} Alumns;
我有一个可能会或可能不会起作用的想法:
while循环读取文件,使用fgets()获取数据。然后它将它复制到结构...但我不知道如何实现任何这个。
很抱歉,如果这听起来像愚蠢的问题,很可能是。
答案 0 :(得分:3)
#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提示实现。
答案 1 :(得分:2)
使用strtok()。 e.g
FILE *fp;
fp = fopen("path", "r");
char string[150];
char *token;
while(!feof(fp)) {
if (fgets(string,150,fp)) {
printf("%s\n", string);
token=strtok(string,",");
/*Store this token in your struct(your first element) */
}
}
3.Remember strtok()是非重入函数,因此存储从strtok()的evey函数调用返回的结果;
答案 2 :(得分:0)
以下是使用fopen()
,fgets()
和strtok()
阅读输入的快速示例,以及如何使用正确的格式字符串格式化输出:(此处显示的输出)
编辑以显示将值放入struct Alums
#include <ansi_c.h>
typedef struct alumnus { //Note "alumnus" is not necessary here, you have Alumns
int yearGraduated; //below that will satisfy naming the typedef struct
char firstName[30];
char lastName[30];
}Alumns;
Alumns a, *pA; //Create copy of struct Alumns to use
#define FILE_LOC "C:\\dev\\play\\file10.txt"
int main(void)
{
FILE *fp;
char *tok;
char input[80];
pA = &a; //initialize struct
fp = fopen(FILE_LOC, "r"); //open file (used #define, change path for your file)
fgets(input, 80, fp);
tok = strtok(input, ", \n"); //You can also call strtok in loop if number of items unknown
pA->yearGraduated= atoi(input); //convert this string in to integer
tok = strtok(NULL, ", \n");
strcpy(pA->firstName, tok); //copy next two strings into name variables
tok = strtok(NULL, ", \n");
strcpy(pA->lastName, tok);
//note the format strings here for int, and char *
printf("age:%d\n First Name: %s\n Last Name: %s\n",
pA->yearGraduated, pA->firstName, pA->lastName);
getchar(); //used so I can see output
fclose(fp);
return 0;
}