简体   繁体   English

在C中解析具有不同大小的行的文本文件

[英]Parsing a Text File with Lines of Different Sizes in C

I have a program that reads lines from a text file and puts it in a list. 我有一个程序可以从文本文件中读取行并将其放入列表中。 The words on each line are categorized as command (add or remove element), position, product and price. 每行上的单词分为命令(添加或删除元素),位置,产品和价格。 They are always in that order. 他们总是按顺序排列。 Some lines do not have price or product, just the command and position. 有些行没有价格或产品,只有命令和位置。 I parse the lines correctly for the first few lines, but if the text file comes short of a few words, for example, doesn't tell us the price or product just the command and postion, I get a segfault. 我为前几行正确地解析了这些行,但是例如,如果文本文件缺少几个单词,仅告诉命令或位置的价格或乘积不告诉我们,则会出现段错误。 Is there a way for me to check if a line from the text file is shorter so that I can only parse the elements that are there? 有没有一种方法可以检查文本文件中的一行是否较短,以便我只能解析其中的元素?

The text file looks something like this: 文本文件如下所示:

add 0 staples 2
add 1 paper 4
add 1 tape 3
add 3 paperclips 2
remove 2
remove 0

The function to parse is as follows. 解析函数如下。

while (fgets (buff, 140, test))
{
    token = strtok(buff, " ");
    instructions = malloc(sizeof(char)*strlen(token)+1);
    strcpy(instructions, token);

    token = strtok(NULL, " ");
    listPosition = atoi(token);

    token = strtok(NULL, " ");
    product = malloc(sizeof(char)*strlen(token)+1);
    strcpy(product,token);

    token = strtok(NULL, " ");
    price = atoi(token);

Use delimiter for each line. 每行使用定界符。 Read each line up to the delimiter then parse that. 读取每一行直到定界符,然后进行解析。 You can also use delimiter after each in the input. 您也可以在每个输入之后使用定界符。 Such as command;product;price; # command;product;price; # command;product;price; # . command;product;price; #

Choose delimiter that wont show up in your normal input youre reading in. 选择不会在您的普通输入中显示的定界符。

  1. Use fgets function gets the line 使用fgets函数获取行
  2. Write a parse function, that takes a line and give you back 4 tokens (command, position, product etc). 编写一个解析函数,该函数需要一行,并给您4个标记(命令,位置,乘积等)。 You can use space as delimeter. 您可以使用空间作为分度符。
  3. Then you know at hand whats present, whats not 然后,您知道手头上有什么,没有什么

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM