从文件中读取并存储在结构中
我想复制此数据@822!172.28.6.137!172.28.6.110!5000!6000|将文件 input_data 形成到此结构中,以将文件中的 822 复制到 input.key 并将 172.28.6.137 复制到 src_ip !遇到它应该将数据从文件复制到结构的下一个成员如何做到这一点?
struct input_par
{
char key[5];
char src_ip[15];
char dst_ip[15];
char src_port[5];
char dst_port[5];
};
main()
{
int i;
char ch;
FILE *fp;
struct input_par input;
fp = fopen("input_data","r");
if(fp == NULL)
printf("file open failed \n");
else
{
ch = fgetc(fp);
if(ch=='@')
printf("data is valid\n");
fseek(fp,1,1);
while(ch!='|')
{
input.key =
input.src_ip =
input.dst_ip =
input.src_port =
input.dst_port =
}
}
i want to copy this data @822!172.28.6.137!172.28.6.110!5000!6000| form file input_data to this structure,to copy 822 from the file to input.key and 172.28.6.137 to src_ip when ever ! is encountered it should copy the data from file to next member of the structure how to do this?
struct input_par
{
char key[5];
char src_ip[15];
char dst_ip[15];
char src_port[5];
char dst_port[5];
};
main()
{
int i;
char ch;
FILE *fp;
struct input_par input;
fp = fopen("input_data","r");
if(fp == NULL)
printf("file open failed \n");
else
{
ch = fgetc(fp);
if(ch=='@')
printf("data is valid\n");
fseek(fp,1,1);
while(ch!='|')
{
input.key =
input.src_ip =
input.dst_ip =
input.src_port =
input.dst_port =
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用正则表达式,请参阅 libstd 中的 regexp.h
如果您必须在这里使用这种东西,您可以直接遍历 char[] 并计算!并根据您之前看到的内容添加您在正确部分中阅读过的字符。
(而且 fscanf 更容易)
You can use regular expressions see regexp.h from libstd
If you just have to use this kind of thing here, you can juste go through your char[] and count the ! and depending and how much you have previously seen you add the chars you've read in the correct section.
(also fscanf is easier)
您可以使用 fscanf。我会做类似的事情:
You can use fscanf. I would do something like:
首先,让我们有一个读取一个字段的函数(尽管它不会检测部分读取的字段)
然后读取字段:
First, let's have a function which reads one field(though it won't detect partially read fields)
Then read the fields:
调用 fscanf 即可完成这项工作:
请注意,您首先必须确保输入字符串不会溢出数组字段。
A call to fscanf will do the job:
Note that you first have to make sure that the input strings do not overflow your array fields.