从文件中读取数据
如何将文件中的数据读取到结构体中? 我有一个类似于
struct data
{
char name[20];
int age;
};
文件 student_info.txt
的结构,等等
ravi 12 raghu 14 datta 13 sujay 10 rajesh 13
,还有许多其他年龄的名字。如何将其从文件读取到结构数据?
读取这个名字和年龄应该是一个循环,即第一次我将读取“ravi”和“12”,然后我应该将这些数据打包到结构中,并在结构设置后立即将结构传递给函数。它应该返回到文件并再次读取“raghu”和“14”,并用这些数据打包结构,这应该处于循环状态,直到我从文件中读取所有数据为止。
任何人都可以告诉我如何实现逻辑吗?
How to read the data from a file to a structure?
I have a structure like
struct data
{
char name[20];
int age;
};
In file student_info.txt
I have
ravi 12 raghu 14 datta 13 sujay 10 rajesh 13
and so on with many other names with ages. How can I read this from file to the structure data?
Reading this name and age should be a loop i.e for the first time I will read 'ravi' and '12', then I should pack this data in the structure and will pass the structure to a function as soon as the structure is set. It should come back to the file and read 'raghu' and '14' again pack the structure with this data, and this should be in a loop till I read all the data from the file
Can anyone please tell how to implement the logic?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
方法是:
代码示例:
The approach is:
An example of the code:
您只需从该文件中读取数据并根据某些条件拆分该字符串即可。由于您的文件格式不正确,您将很难解析数据。
在当前场景中,您的文件仅包含名字和数字,您可以通过检测字符串中的空格字符来轻松解析它。但如果您的任何名字包含空格,这可能会导致问题。
首先,用一些字符分隔每对单词,例如 : 或 ;或制表符或换行符。
然后在每个分隔的字符串之间用空格将其分割,然后读取字符数组中文件的所有内容,然后从该数组中尝试找到指示一条记录的特殊字符。
将每个记录分隔在不同的字符数组中,然后再次针对每个生成的数组,然后根据空格字符将其拆分并加载到结构中
这只是为了解释,原始实现可能有所不同,
希望该文档能够解决您的问题 http://www.softwareprojects.com/resources//t-1636goto.html
You just need to read data from this file and split that string based on some criteria. as your file is not properly formatted it would be difficult for you to parse data.
In your current scenario your file contain only first name and a digit you can easily parse this by detecting a Space Character in your string. but this could lead a problem if any of your name contains a space.
First of all separate each pair of word by some character such as : or ; or a tab or line break.
then between each separated string split it by space and then read all content of file in a char array then from that array try to find that special character which indicates one record.
Separate each record in a different char array then for each generated array again and then split it based on space char and load in your struct
This is just for explanation, original implementation may be different,
Hope that document solves your problem http://www.softwareprojects.com/resources//t-1636goto.html