如何将文本文件中的数据直接转换为结构指针?我试着这个,但我不能让它工作,文本文件的例子可以是:
A 100
K 55
C 300等
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
struct myStruct
{
char singleChar[10];
int height;
};
int main (void) {
FILE * fp;
char buffer[50];
int counter = 0;
char a[10];
int res;
int b;
struct myStruct **list;
list = malloc(sizeof(struct myStruct));
fp = fopen("test.txt","r");
while (fgets(buffer,50,fp)!= NULL)
{
res = sscanf(buffer, "%c%d",a,&b);
if (res == 2)
{
list[counter] = malloc(sizeof(struct myStruct));
strcpy(list[counter]->singleChar,a);
list[counter]->height = b;
counter++;
}
}
printf("%d",list[0]->height);
return 0;
}
答案 0 :(得分:0)
如果您不知道文件的大小,则必须对其进行完整传递以确定其长度,然后再次扫描以将数据加载到结构中:
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
struct myStruct
{
char singleChar[10];
int height;
};
int main (void) {
FILE * fp;
int counter = 0;
char a[10];
int b, i;
int file_length = 0;
fp = fopen("test.txt","r");
while (fscanf(fp, "%c%d\n",a,&b) > 0){
printf("%c,%d\n",a[0],b);
file_length += 1;
}
printf("There are %d entries\n",file_length);
struct myStruct *list[file_length];
fclose(fp);
fp = fopen("test.txt","r");
while ( fscanf(fp, "%c%d\n",a,&b) > 0 ){
list[counter] = malloc(sizeof(struct myStruct));
strcpy(list[counter]->singleChar,a);
list[counter]->height = b;
counter += 1;
}
for ( i = 0 ; i < file_length ; i++ ){
printf("%c,%d\n",list[i]->singleChar[0],list[i]->height);
free(list[i]);
}
return 0;
}
另一种方法是分配使用realloc。
为什么在struct中使用char数组而不是单个char?
答案 1 :(得分:0)
您可能想要使用链接列表:
#include <stdio.h>
#include <stdlib.h>
struct List
{
char c;
int i;
struct List* lp;
};
typedef struct List LinkedList;
_Bool first_time_here=1;
LinkedList *head,*tmp;
int main(void)
{
char tempc,nl;
int tempd;
LinkedList* ptr;
LinkedList* current=NULL;
FILE* fp;
if((fp=fopen("36229327.txt","r"))!=NULL)
{
printf("Contents from file\n");
while(fscanf(fp,"%c%d%c",&tempc,&tempd,&nl)>0)
{
printf("%c %d\n",tempc,tempd);
ptr=malloc(1*sizeof(LinkedList));
if(ptr != NULL)
{
if(first_time_here)
{
head=ptr;
first_time_here=0;
}
ptr->c=tempc;
ptr->i=tempd;
ptr->lp=NULL;
if(current!=NULL)
{
current->lp=ptr;
}
current=ptr;
}
else
{
printf("Can't allocate memory\n");
printf("Aborting\n");
}
}
fclose(fp);
printf("\nFile Closed\n\n");
if(head!=NULL)
{
current=head;
printf("File contents retrieved from Linked List\n");
while(current!=NULL)
{
printf("%c %d\n",current->c,current->i);
tmp=current;
current=current->lp;
free(tmp); // clearing the allocated memory
}
}
}
else
{
printf("Can't open file\n");
exit(-1);
}
return 0;
}
从代码中可以看出,内存是按需创建的,并在使用后释放。
假设:文件内容的存储方式与问题中给出的完全相同 在行尾没有多余的空格。