倒带文件,创建动态结构体

编程入门 行业动态 更新时间:2024-10-23 16:25:12
本文介绍了倒带文件,创建动态结构体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

此功能将倒带文件,创建动态数组(大小),并在数据读取,填充_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); }

更多推荐

倒带文件,创建动态结构体

本文发布于:2023-07-11 09:15:12,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1093548.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:结构   文件   动态

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!