本文介绍了倒带文件,创建动态结构体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
此功能将倒带文件,创建动态数组(大小),并在数据读取,填充_data结构动态数组。需要注意的是流按值这个时候过去了。该函数然后返回填充结构的阵列
this function will rewind file, create the dynamic array (of size), and read in the data, populating the _data struct dynamic array. Note that stream is passed by value this time. The function then returns the populated array of struct
struct _data { char* name; long number; }; struct _data *load(FILE *stream, int size) { struct _data BlackBox = calloc(size, sizeof(_data)); char tempName[3]; stream = fopen("names.txt", "r"); for (int i=0; i<size; i++) { fscanf(stream, "%s %ld", tempName, &data.number); BlackBox[i].name = calloc(strlen(tempName), sizeof(char)); strcpy(BlackBox[i].name, tempName); } fclose(stream); return &BlackBox; } File Content ron 7774013 jon 7774014我是初学者和有困难的设计code。有人可以请解释。谢谢
I am a beginner and having difficulty designing the code. Can someone please explain. Thanks
推荐答案我觉得你有从GCC一定的警示作用来帮助你。
I think you have some warning from gcc to help you.
修复内存管理与释放calloc,不返回堆栈指针
Fix memory management with your calloc, and don't return a stack pointer
typedef struct _data { char* name; long number; } _data; _data *load(FILE *stream, int size) { _data *BlackBox = calloc(size, sizeof(_data)); char tempName[3]; for (int i=0; i<size; i++) { fscanf(stream, "%s %ld", tempName, &BlackBox[i].number); BlackBox[i].name = strdup(tempName); } fclose(stream); return BlackBox; } int main (void) { FILE *f = fopen("test.data", "r"); _data *data = load(f, 2); printf("%s %ld\n", data[0].name, data[0].number); printf("%s %ld\n", data[1].name, data[1].number); return 0; }输出
aurel@vm-pontarlier:~$ ./a.out ron 7774013 jon 7774014考虑变革_data
typedef struct _data{ char name[256]; long number; } _data;扫描将是:
for (int i=0; i<size; i++) { fscanf(stream, "%s %ld", BlackBox[i].name, &BlackBox[i].number); }更多推荐
倒带文件,创建动态结构体
发布评论