[英]Using fread() to read struct
i am trying to use fread to enter data to this structure, i have defined this structure as an header like this 我正在尝试使用fread将数据输入此结构,我已将此结构定义为这样的标题
#ifndef__HEADER_H__
#define__HEADER_H__
struct input_par
{
char key[5];
char key_node[5];
char src_ip[15];
char dst_ip[15];
char src_port[5];
char dst_port[5];
};
#endif
in my main function, in file input_data i have stored this data 在我的主要功能中,我在文件input_data中存储了此数据
@822!822!172.28.6.137!172.28.6.110!5000!6000|
for me @ means start of the data and | 对我来说@表示数据的开始,| means end of valid data here i want to enter 822 to key, 822 to key_node, 172.28.6.137 to src_ip and so on 6000 to dst_port, i am not able to do this for testing purpose i am just entering only 822 to key. 意思是有效数据的结尾,我想输入822,输入822到key_node,172.28.6.137输入src_ip,等等,输入6000到dst_port,我不能出于测试目的而这样做,我只输入822即可。 I am using fread for the first time please help 我是第一次使用fread,请帮忙
#include"file_header"
#include <stdio.h>
main()
{
int i;
struct input_par input_par;
FILE *fp;
fopen("input_data","r");
if(*fp == "@")
{
while(*fp!= "!")
{
for(i=0;i<5;i++)
{
fread(&input_par.key, sizeof(input_par),1,fp);
printf("%d\n",input_par.key);
}
}
}
fclose(fp);
}
Well, you have some errors in your code. 好吧,您的代码中有一些错误。 As @unaperson pointed out, that is not the use of FILE, and definitely you should learn about it . 正如@unaperson指出的那样,这不是使用FILE,并且绝对应该了解它 。
If you are going to read each char in the file, and interpret @ as a delimiter, you can use fgetc instead of fread, which is used for reading big chunks. 如果要读取文件中的每个字符,并将@解释为定界符,则可以使用fgetc而不是fread来读取大块数据。 Be aware that fgetc returns an int, in order to be able to check the end-of-file error condition (you cannot read anymore). 请注意,fgetc返回一个int,以便能够检查文件结束错误状态(您无法再读取)。
You can read each field until the next delimiter, and store it in the appropriate field of your struct. 您可以阅读每个字段,直到下一个定界符,然后将其存储在结构的适当字段中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.